tags:

views:

133

answers:

3

I'm new to ASP.NET MVC so this could have an obvious answer. Right now I have a form in my view with a lot of input controls, so I have an action that looks like this:

public ActionResult MyAction(string formItemOne, int? formItemTwo, etc...)

It has like a dozen parameters, which is pretty ugly. I'm trying to change it to this:

public ActionResult MyAction(FormCollection formItems)

and then parse the items dynamically. But when I change to a FormCollection, the form items no longer "automagically" remember their values through postbacks. Why would changing to a FormCollection change this behavior? Anything simple I can do to get it working automagically again?

Thanks for the help,

~ Justin

A: 

Maybe because they aren't magically inserted into the ModelState dictionary anymore. Try inserting them there.

If you use UpdateModel() or TryUpdateModel() I think the values are gonna be persisted.

Kim Johansson
+4  A: 

Another solution is to use models instead of manipulating the raw values. Like this:

class MyModel
{
  public string ItemOne { get; set; }
  public int? ItemTwo { get; set; }
}

Then use this code:

public ActionResult MyAction(MyModel model)
{
  // Do things with model.

  return this.View(model);
}

In your view:

<%@ Page Inherits="System.Web.Mvc.ViewPage<MyModel>" %>
<%= Html.TextBox("ItemOne", Model.ItemOne) %>
<%= Html.TextBox("ItemTwo", Model.ItemTwo) %>
Kim Johansson
+1  A: 

To replace your big list of parameters with a single one, use a view model. If after the POST you return this model to your view, then your view will remember the values posted.

A view model is simply an class with your action parameters as public properties. For example, you could do something like this, replacing:

public ActionResult MyAction(string formItemOne, int? formItemTwo, etc...)

with

public ActionResult MyAction(FormItems formItems)
{
  //your code...
  return View(formItems);
}

where FormItems is

public class FormItems
{
  public property string formItemOne {get; set;}
  public property int? formItemTwo {get; set;}
}

You may see a complete example in Stephen Walter's post ASP.NET MVC Tip #50 – Create View Models.

eKek0