Inserting and removing items from the collection ASP.NET MVC Part 1 (Tutorial + Code)

As promised in the previous post, this tutorial will show how to create a Helper to handle collections.



For starters if you have not already done so, read the previous post to show how to eliminate the indexes in collections in ASP.NET MVC. I will use as an example the Person (Person) and classes Phones (Phone) where one can have 1 or more phones, a separate edition of the phones that you can view using ASP.NET MVC Editor Templates must be created.





To play you must create a folder called EditorTemplates within the view you add a folder with the same name of the Model, which in this example is Phone. Create a view as below:


The divs involving field is not mandatory.

In view of creation, the Person model, you must cite the editor of phones, as example below:


Now let's create the Helper. Create a static with the name HtmlHelpers class. Within this class create a method as below:



This will be responsible for adding one more field method. This method is an extension of the HtmlHelper class, and receives as parameters the name that should appear on the link, the container where the new field is included, the collection name and type of the collection.

1st line an instance of the collection using the same type is created.



In the 2nd line it creates a view that will be added. This line makes a call to the JsEnconde method, used to make adjustments to the generated html, the code of this method is somewhat extensive and how the code will be available will not show it here.




In the 3rd line is made ​​a replace to add the correct name of the property field. 


In 4th line call Javascript function that will be responsible for actually adding the new field is created.


As we saw above field will be added via Javascript, create a script for it and add the following function:



Returning to the helper, add the following lines:



In the above lines to create the link element is taken, receiving as parameters the name of the link and the call to the JavaScript function.

In reference to the view helper and model.


Shortly after the call to make the helper. Note that the parameter refers to the container is nothing but the id where the new fields will be added.

In part 2 I will demonstrate the procedure for removing and validation of new fields.

The full project is here: https://github.com/rafaelguinho/AddRemove

0 comentários:

Postar um comentário