Search code examples
asp.netasp.net-mvc-3routevalues

Reading in RouteValues to Controller


so I have a Url Action

<a href="@Url.Action("Create","Teacher", new { createAndAssign = true, teacherID = Model.AccountID })">Create new teacher & assign to account.</a>

That passes in two routeValues: createAndAssign, and teacherID.

Now when I go to my Teacher/Create page, my URL is like so:

.../Teacher/Create?createAndAssign=True&teacherID=ea817321-5633-4fdc-b388-5dba2c4a728e

Which is good, I want this. Now when I POST to create my teacher, how do I grab createAndAssign and teacherID value?


Solution

  • You can set the Querystring value in a hidden variables in the form and render in your GET action method and accept that in your POST action method.

    View rendered by your GET Action

    @using (Html.BeginForm())
    {
     //Other form elements also
      @Html.Hidden("teacher",@Request.QueryString["teacherID"] as string)
      @Html.Hidden("createAndAssign",@Request.QueryString["createAndAssign"] 
                                                                        as string)
      <input type="submit" />
    }
    

    and now have a teacher parameter and createAndAssign parameter in your HttpPost action method so that it will be available when you submit the form.

    [HttpPost]
    public ActionResult Create(string teacher,string createAndAssign)
    {
         //Save and Redirect      
    }
    

    If your view is strongly typed (which is my personal preference), it is quite easy,

    public ActionResult GET(string teacherID,string createdAndAssing)
    {
       var yourVMObject=new YourViewModel();
       yourVMObject.TeacherID=teacherID;
       yourVMObject.CreateAndAssign=createdAndAssing;
       return View(createdAndAssing);
    }
    

    and in your strongly typed view,

    @model YourViewModel
    @using (Html.BeginForm())
    {
     //Other form elements also
      @Html.HiddenFor(x=>x.TeacherID)
      @Html.HiddenFor(x=>x.CreateAndAssign)                                     
      <input type="submit" />
    }
    

    And in your POST action

    [HttpPost]
    public ActionResult Create(YourViewModel model)
    {
         //look for model.TeacherID
         //Save and Redirect      
    }