在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Adding new Item to a list of items, inline is a very nice feature you can provide to your user. This posts shows 2 different ways to do this in ASP.NET MVC3 and how Modelbinding handles that. MVC3 dynamically added form fields model bindingWe are going to create a new page where it lists the various Programming Interests a user has. The user will have an option to add a new Record ( Programming interest) to the list present. Let’s create 2 ViewModels(ViewModel is a simple POCO class) for our views. Add the below 2 classes to our project.
Now I am going to create a
This action is simply creating an object and setting the Name property and Setting the Interests collection. Now to handle the collection Property of our Model, Let’s create an Editor template called Now we will use
We are done with that. Running the project will show the output like this. note that this does not have any feature for the user to add the new record to the collection. Adding Record InlineI am going to make some changes to our view. 1) Add a button called ” Add new Item ” to our html markup. <input type="button" /> 2) Add some javascript code to create the form fields when user clicks on the Add New Item button and append that to our table which holds the collection.
So the result of running our updated project will be like this. there is a “Add New Item” button and clicking that will add new record to our existing table. Now When the user posts the form, the MVC Model binding feature will bind the newly added items as well. You can check that by putting a breakpoint in the HttpPost action method.
The trick is to keep the id property value of the html element in this format.
and name property value in this format
If your Collection item has many fields, It will be hard to write javascript code for creating the form elements. In that case, You may consider doing it in the server side. So i will update my javascript code like this.
You can see that we are not building the html in our client side code here. Instead we are mkaing an ajax call to the
It simply creates an object of our
This View also creates the same HTML elements we created at client side previously, with the same name /ID convention we need for the Model binding to work.
Summary : Here we showed 2 ways to add dynamic form fields to an existing collection which gives a nice user experience and how MVC Model binding works for those new elements. The main thing to remember is to keep the format of the name and id property values. Model binding will work for the new elements only if they follow the format. You can download the sample source code here to see how it works.
Reference: http://www.techiesweb.net/asp-net-mvc3-dynamically-added-form-fields-model-binding/ |
请发表评论