-2

How to make an action in a controller to receive more data from an unknown number of inputs?

I want when click on more option for enter more information that is mean the DOM tree on HTML page is increasing for that I do not know how to make action receive data from an unknown number of inputs on HTML page.

This is my codes of html

<div class="form-group">
<label class="col-md-2 lableAlign">Course Name</label>
<div class="col-md-6">
<input class="col-md-6" type="text" name="courseTitle" id="courseTitle" value="Thamar" maxlength="20">
@Html.ValidationMessageFor(model => model.courseTitle, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
<label class="col-md-2 lableAlign">Certificate</label>
<div class="col-md-6">
<input class="col-md-6 r" type="file" name="courseCertificate" id="courseCertificate" val`enter code here`ue="">
@Html.ValidationMessageFor(model => model.courseCertificate, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group more" id="corceMore">
<label class="col-md-3 more" onclick="corceAdd()">More +</label>

</div>

And this is my javascript code

function corceAdd() {
++corcecount;
if (corcecount < 20) {
        $("<div class=\"divStyle\"><div class=\"form-group\"><label class=\"col-md-2 lableAlign\">اسم الدورة</label><div class=\"col-md-6\"><input class=\"col-md-6\" type=\"text\" name=\"corceTitle" + corcecount + "\" id=\"corceTitle" + corcecount + "\" value=\"\"></div></div><div class=\"form-group\"><label class=\"col-md-2 lableAlign\">الشهادة</label><div class=\"col-md-6\"><input class=\"col-md-6 r\" type=\"file\" name=\"corceCertificate" + corcecount + "\" id=\"corceCertificate" + corcecount + "\" value=\"\"></div></div>").insertBefore("#corceMore");

}
}

when click on more option the new element its id and name with increasing by one , Now my problem is when I click on submit I want send all elements values to a post action in a controller .

1 Answers1

0

There are lots of articles and topics about this question:

http://techiesweb.net/2012/09/17/asp-net-mvc3-dynamically-added-form-fields-model-binding.html

ASP.NET MVC Dynamic Forms

I will show the main point. How to bind dynamically input to action model.

You need to have a collection as a model.

public class SampleViewModel
{
  public IEnumerable<SampleItemViewModel> Items {get;set;}
}

public class SampleItemViewModel
{
   public string Id {get;set;}
}

Then in the Razor view you should create an input like this:

<input id='Items__0__Id' type='hidden' name='Items[0].Id' />
<input id='Items__1__Id' type='hidden' name='Items[1].Id' />

So you should bind name of the input to the property of the collection with index. Then in your action:

public ActionResult Post(SampleViewModel model)
{
   var items = model.Items; // Here you should have your collection
} 
Iaroslav
  • 295
  • 1
  • 10