WookieCoder WookieCoder - 4 years ago 163
HTML Question

Retrieve entire model from view

I have an ASP.NET MVC project, where I am using a model class. I have about 10 variables I need to get from my controller to the view and then back to the controller. Currently, I have been storing them in the model, reading the variables into hidden input fields, and then using a

NameValueCollection
like this:




Html:

<input type="hidden" id="field1" name="field1" value="@Model.variable1" />
<input type="hidden" id="field2" name="field2" value="@Model.variable2" />
<input type="hidden" id="field3" name="field3" value="@Model.variable3" />
<input type="hidden" id="field4" name="field4" value="@Model.variable4" />
<input type="hidden" id="field5" name="field5" value="@Model.variable5" />
<input type="hidden" id="field6" name="field6" value="@Model.variable6" />


C#

System.Collections.Specialized.NameValueCollection nvc = Request.Form;
model.variable1= int.Parse(nvc["field1"]);
//read the rest of the data into the model


Note: the
values
s and
name
s have been edited for simplicity




Is there a better way to do this? Ideally, I would like to pass my entire model back to my controller, but I have looked for a solution with no success.

Answer Source

There's no need to manually code html inputs or parse data directly from the Request.Form object. The MVC framework does all of that internally for you.

public class MyModel 
{
    public string Variable1 {get;set;}
    public string Variable2 {get;set;}
    //....

}

View:

The special thing about these methods that end with For is that when you specify a property of your model they are going to use build you an html input with the correct id and name attributes.

@model MyModel
@Html.HiddenFor(x=> x.Variable1)
@Html.HiddenFor(x=> x.Variable2)
//...

Controller action:

[HttpGet]
public ActionResult SomeAction()
{
     var model = new MyModel();
     model.Variabl1 = "hi";

     return View(model);
}

[HttpPost]
public ActionResult SomeAction(MyModel model)
{
    model.Variable1
}

You can also send down Lists of custom objects and persist them when you post back, but that's a bit more complex and out of scope for this answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download