问题
this is my controller:
public ActionResult Create() {
Number newNumber = new Number();
return View(newNumber);
}
and View :
@model PhoneBook.Models.Number
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="../../Scripts/jQuery.AddNewNumber.js" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Contact.Id)
<fieldset>
<legend>Number</legend>
<div class="TargetElements">
<div class="editor-label">
@Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PhoneNumber)
@Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.NumberKind)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.NumberKind.Title, NumberKinds)
</div>
</div>
<p>
<input class="AddNew" value="Add New" type="button" /></p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
By press AddNew button (use jQuery AddNewNumber.js) new input+DropDown Added to form in client side. But there is a problem in retrieve values, When I have one entry element(include input+DropDown) I can retrieve values like the following in post of my controller:
[HttpPost]
public ActionResult Create(Number NewNumber, FormCollection collection) {
db.Numbers.Add(NewNumber);
db.SaveChanges();
return RedirectToAction("Index")
}
But when there is multi-entry how can I retrieve values and add them to DataBase?
回答1:
Use by the name of element like this:
string[] PhoneNumbers = collection.GetValues("PhoneNumber");
回答2:
You want all of your input elements to have the same name. Then in your POST action method, the parameter would be List. Here is an example: Model Binding to a List of objects
来源:https://stackoverflow.com/questions/8164257/mvc-retrieve-multi-entry-from-view-in-controller