Http Post with duplicate name values MVC

1.6k Views Asked by At

In MVC I have a form that uses a lot of duplicate information. Basically they click a button and there is another "form"(text box drop down list etc) that pops up. When they click the submit button however all of that comes back with the same name. How would I go about either making the names different in the Post or be able to throw the items into a list?

My code:

@Html.TextBox("Textbox1", "", new { placeholder = "", size = "77", maxlength = "76" })
@Html.DropDownList("Country", ViewData["CountryOptions"] as SelectList,"Select", new { id = "Country"})</div>
<div class="pad5">
<span class="FieldLabel">Application *</span><span>@Html.DropDownListFor(model => model.ProductsID, Model.HowProductsAreUsedOptions, new { @class = "General", id = "General-1" })
@Html.DropDownListFor(model => model.ApplicationValue, Model.Options, "--Choose One--", new { id = "Option1", style = "display:none" })
</div>

These can be repeated up to 9 times by the time they submit. However this will give me this in the Post

FormID=8&Textbox1=This&Country=USA&ProductsID=1&ApplicationValue=2&
Textbox13=Is&Country=Canada&ProductsID=2&ApplicationValue=3&
Textbox14=A&Country=Canada&ProductsID=2&ApplicationValue=1&
Textbox15=Test&Country=Canada&ProductsID=1&ApplicationValue=8&
Textbox16=For&Country=Canada&ProductsID=2&ApplicationValue=1&
Textbox17=Stack&Country=USA&ProductsID=1&ApplicationValue=9&
Textbox18=Overflow&Country=USA&ProductsID=2&ApplicationValue=2

How can I make something so that way it will be able to seperate these into 7 different value sets instead of only giving me one of each?

1

There are 1 best solutions below

0
On BEST ANSWER

If I were you I would create a strongly typed view model to represent your data.

One to represent each item with the properties within them.

public class FooModel
{
    public string Text { get; set; }
    public string Country { get;set;}
    public int ProductsID { get; set; }
    public int ApplicationValue { get; set; }
}

Then create a model to hold them and represent them

public class FooViewModel
{
   public List<FooModel> Foos { get; set; }
}

You can then return an instance of FooViewModel from your controller.

Within your view you use the name indexing of the collection as follows:

@for (var i = 0; i < Model.Foos.Count; i++) 
 {
      ...
      @Html.TextBoxFor(model => Model[i].Text)
      @Html.DropDownListFor(model => Model[i]Country, ViewData["CountryOptions"] as SelectList,"Select")
      @Html.HiddenFor(model => Model[i].ProductsID)
      ...
 }

The HiddenFor's will post those values back too.

Now in your action you just need to change your parameter to take an instance of FooViewModel and they will all be populated server side.

For more info on it see here:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/