I have a need to be able to post back an unknown number of this model class:
public class UserRegisterModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string RepName { get; set; }
public string ContactNumber { get; set; }
}
in a List<UserRegisterModel>
to a controller.
I need my view to have a form that can send back multiple instances of the model to the controller, so for example if my user wants to add 3 Reps, he can make 3 reps and give them each details and usernames and passwords, and send them all back at once in a List.
I have this starting point for my view code:
@model List<PicsWebApp.Models.UserRegisterModel>
@{
ViewBag.Title = "NewRep";
}
<h2>NewRep</h2>
@using (Html.BeginForm("NewRep", "Admin", FormMethod.Post, new { id = "fieldform", @class = "form" }))
{
}
Can anybody show me the correct way of accomplishing this? I know I need javascript in order to dynamically add more form elements if the user clicks "add new rep" so this is mainly about the C#.
you need to make sure the properties' ID's conform to the standard set (I used the link from Felipe's comment when I was doing this). I did this before, where a table row would get added when the user click a button. I found the best way is to add an entry before the page gets rendered, then taking the HTML for that, and using it in your jquery.
Here's a function I've used:
$("#nameAdd").click(function (e) {
var index = $("#nameTable tr").length - 1;
e.preventDefault();
var newItem = $("<tr> \
<td> \
<span id='Names_" + index + "__FullName' /> \
</td> \
<td> \
<input class='table-editor-small update-name' id='Names_" + index + "__FirstName' name='Names[" + index + "].FirstName' type='text' value='' /> \
</td> \
<td> \
<input class='table-editor-small update-name' id='Names_" + index + "__MiddleName' name='Names[" + index + "].MiddleName' type='text' value='' /> \
</td> \
<td> \
<input class='table-editor-small update-name' data-val='true' data-val-required='Person Last Name Required' id='Names_" + index + "__LastName' name='Names[" + index + "].LastName' type='text' value='' /> \
</td> \
<td class='center'> \
<input data-group='nameRadios' id='Names_" + index + "__IsPrimary' name='Names[" + index + "].IsPrimary' type='radio' value='True' /> \
</td> \
<td class='center'> \
<input data-val='true' data-val-required='The Delete? field is required.' id='Names_" + index + "__ToDelete' name='Names[" + index + "].ToDelete' type='checkbox' value='true' /> \
<input name='Names[" + index + "].ToDelete' type='hidden' value='false' /> \
</td> \
</tr>");
$("#nameTable").append(newItem);
}
again, the HTML to add is straight from an item that had been rendered by the view, i just swapped in the index
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.