2012-05-11 25 views
7

Tengo un problema al usar el método RedirectToAction en mvc. La ruta de mi mapa se ve así.Cómo usar RedirectToAction correcto

   routes.MapRoute(
     "Project", // Route name 
     "{Controller}/{Action}/{projectId}/{machineName}/{companyId}", 
      new { controller = "Project", action = "Directives", projectId = 0, machineName = "", companyId = 0 } // Parameter defaults); 

Y el regreso este aspecto:

return RedirectToAction("Directives", "Project", new { projectId = projectId, machineName = project.MachineName, CompanyId = user.Company_Id }); 

Funciona prefecto, pero la utilizo el RedirectToAction todavía se ve como este

http://localhost:1843/Project/Directives?projectId=48&machineName=Netduino&companyId=27 

controlador:

 [HttpPost] 
    [ValidateInput(false)] 
    public ActionResult Create(Project project, string text) 
    { 
     ViewBag.MachineType = new List<string>(new string[] { "Machine Type A", "Machine Type B", "Machine Type C", "Machine Type D", "Machine Type E" }); 

     if (ModelState.IsValid) 
     { 
      UserAccess user = (UserAccess)(Session["UserAccessInfo"]); 

      Int64 projectId = DataBase.DBProject.InsertProject(project.ProjectNumber, project.MachineName, project.MachineNameEnglish, 1, project.Serial, text, user.Company_Id,project.MachineType); 

      return RedirectToAction ("Directives", "Project", new { projectId = 48, machineName = "Netduino", companyId = 27 }); 
      // return RedirectToAction("Directives", "Project", new { projectId = projectId, machineName = project.MachineName, CompanyId = user.Company_Id }); 
     } 
     else 
     { 
      ModelState.AddModelError("", "Invalid username or password"); 
     } 

     return View(); 

    } 

La recepción controlador:

public ActionResult Directives(int projectId, string machineName, int companyId) 
    { 
     convertedDirectives = new List<Models.Directives>(); 
     ViewBag.MachineName = machineName; 
     ViewBag.ProjectId = projectId; 
     List<object> Directives = new List<object>(); 

     if (ModelState.IsValid) 
     { 
      Directives = DataBase.DBProject.GetDirectives(companyId); 
      foreach (List<object> dir in Directives) 
      { 
       Directives newDirective = new Models.Directives(); 
       newDirective.CompanyID = Convert.ToInt32(dir[0]); 
       newDirective.DirectiveId = Convert.ToInt32(dir[1]); 
       newDirective.Id = Convert.ToInt32(dir[2]); 
       newDirective.DirectiveName = Convert.ToString(dir[3]); 
       newDirective.DirectiveNameShort = Convert.ToString(dir[4]); 
       newDirective.Created = Convert.ToDateTime(dir[5]); 

       convertedDirectives.Add(newDirective); 
      } 
     } 
     else 
     { 
      ModelState.AddModelError("", "An error has "); 
     } 

     ViewBag.DirectivesList = convertedDirectives; 
     return View(); 
    } 

Pero la forma en que quiero es así.

http://localhost:1843/Project/Directives/48/Netduino/27 

Pero lo extraño es que puedo escribir manualmente en la Url y funciona perfectamente. ¿Qué estoy haciendo mal?

Respuesta

4

Tengo algunos consejos.

Primero, no nombre sus rutas. Pase nulo a ese primer argumento. Hay varias sobrecargas de RedirectToRoute que toman un nombre de ruta, y RedirectToAction devuelve un RedirectToRouteResult.

En segundo lugar, no proporcione los valores predeterminados a los parámetros requeridos. Si desea tener un valor predeterminado, proporcione un valor predeterminado solo para el último parámetro.

routes.MapRoute(null, // don't name the route 
    "{controller}/{action}/{projectId}/{machineName}/{companyId}", 
    new 
    { 
     controller = "Project", 
     action = "Directives", 
     //projectId = 0, 
     //machineName = "", 
     //companyId = 0, 
    } 
); 

En tercer lugar, en caso de duda, tratar de devolver un RedirectToRoute lugar. Pasar el controlador, la acción, y el área (si es aplicable), junto con sus otros parámetros:

return RedirectToRoute(new 
{ 
    controller = "Project", 
    action = "Directives", 
    // area = "SomeAreaName", // if the action is in an area 
    projectId = projectId, 
    machineName = project.MachineName, 
    companyId = user.Company_Id, 
}); 

Por último consejo es utilizar T4MVC para deshacerse de esas cadenas mágicas.

routes.MapRoute(null, // don't name the route 
    "{controller}/{action}/{projectId}/{machineName}/{companyId}", 
    new 
    { 
     controller = MVC.Project.Name, 
     action = MVC.Project.ActionNames.Directives, 
    } 
); 

podrá usar esos mismos tipos fuertes en RedirectToRoute, o puede utilizar los parciales T4MVC para devolver a las acciones:

return RedirectToAction(MVC.Project.Directives 
    (projectId, project.MachineName, user.Company_Id)); 
+0

Hola. Por alguna razón, todavía no puedo hacer que funcione correctamente. He agregado mi Controlador que envía los datos – mortenstarck

+1

. Lo acabo de hacer funcionar. El problema fue en varios lugares. 1. En el archivo Global.asax.cs necesito especificar algo así '" Project/{action}/{machineName}/{projectId}/{directiveId}/{directiveName} "'. Y usé su sugerencia de usar RedirectToRoute en lugar de ToAction y luego trabajé. – mortenstarck

0

Cuando pruebo su ruta y RedirectToAction(), funciona correctamente cuando corrijo el caso de la propiedad "CompanyId" en el objeto anónimo a "companyId".

return RedirectToAction("Directives", "Project", new { projectId = 48, machineName = "Netduino", companyId = 27 }); 

Actualización: Aquí está el código de global.asax, los controladores, y la vista.

routes.MapRoute(
      "Project", // Route name 
      "{Controller}/{Action}/{projectId}/{machineName}/{companyId}", 
       new { controller = "Project", action = "Directives", projectId = 0, machineName = "", companyId = 0 } // Parameter defaults 
); 

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return RedirectToAction("Directives", "Project", new { projectId = 48, machineName = "Netduino", companyId = 27 }); 
    } 
} 

public class ProjectController : Controller 
{ 
    public ActionResult Directives(int projectId, string machineName, int companyId) 
    { 
     ViewBag.ProjectId = projectId; 
     ViewBag.MachineName = machineName; 
     ViewBag.CompanyId = companyId; 
     return View(); 
    } 
} 

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    Directives 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
    <h2> 
     Directives</h2> 
    <%: ViewBag.ProjectId %><br /> 
    <%: ViewBag.MachineName %><br /> 
    <%: ViewBag.CompanyId %><br /> 

    <%: this.Request.RawUrl %> 
</asp:Content> 
+0

¿Qué está haciendo mal im. Todavía no puedo hacerlo bien. Pero si escribo la url en correcto, también funciona – mortenstarck

Cuestiones relacionadas