How to pass Formcollection and Model value at the same time from view to controller?

16.5k Views Asked by At

I have cshtml page having code like this

model Kouponer.Models.person_T  
@using (Html.BeginForm("BuynowForm", "Home"))
{    
    <label>@Model.name</label>
    <label>address</label>
    @Html.TextBox("address")<div>
    <input type="submit" value="Submit" class="btn btn-primary" />
}

And my current actionresult method is

[HttpPost]
public ActionResult BuynowForm(FormCollection col)
{  string address = col["address"];
        return View();
}

Here I will get only the formcollection values. How to pass the model along with the formcollection?

2

There are 2 best solutions below

3
On

In the Controller class of System.Web.Mvc namespace there is an HttpRequestBase property called Request with all the data of the current http request. Among its properties, there is the NameValueCollection property called Form you are looking for.

The usage would be something like this:

[HttpPost]
public ActionResult BuynowForm(person_T model)
{
    string addressFromModel = model.Address;
    string addressFromRequest = Request.Form["address"];
    return View();
}
0
On

Unless I'm completely missing something, you should simply be able to add the model type on the controller's sig.

[HttpPost]
public ActionResult BuynowForm(Models.person_T model, FormCollection col)
{  string address = col["address"];
   string addressFromModel = model.Address;
   return View();
}

However, it seems redundant to need the FormCollection object if you are going to be using model binding. I would read the link given in the comments and just go with model binding.