Friday, January 7, 2011

Using EditorTemplates with Generic Lists in ASP.NET MVC2 (getting that list back in a PostBack with data!!)

The following example will show you how to bind a generic list (List) to an Edit View using an EditorTemplate. This is key in order to save you a ton of time, as well as getting the list back on post with edited values intact.

1. We'll start with a new ASP.NET MVC 2 Web Application, called EditorTemplate. We'll choose no to Unit Tests, as we won't need them for this example.



2. Create a new Model called Test, and give it 2 properties: Name & Message. We'll just be using a very basic example here, nothing too fancy.



3. In our Home Views folder, we'll add a new folder called EditorTemplates. The folder must be named EditorTemplates as MVC will look for this naming convention when using your template.



4. Right click on the folder and select Add -> View. We'll call it TestEditorTemplate and make it a partial view. Your editor template must be a Partial View.



5. Now, we'll add our markup to the Editor Template. First, it needs to inherit our Model (EditorTemplate.Models.Test). Then we just add TextBoxFor for each item in our Model.



6. In our Index View we'll inherit a List. Next we need to add a For Loop to loop through all the items in our List and pass them off to our Editor Template. The loop is pretty straight forward, each time through we simply request the template using an Html.EditorFor, passing in the current object by its index. The Html.EditorFor takes the object to bind and the name of the EditorTemplate. As long as you have a folder named EditorTemplates in the current View folder, MVC will find the named template and use it. We'll also add a Save button to facilitate the PostBack.



7. In our HomeController, we'll need to create a List and pass this to the Index View. A simple For Loop will suffice here to populate the list. We'll also create an Index HttpPost method to get our list back. As you can see, we just declare that we are expecting a List back on the PostBack.



8. Save this and run the application. The resulting page is ugly, but you can see that it took our List and bound each object to the TestEditorTemplate.



9. We'll set a break point on the Index Post method. Change some data in each textbox, and then click the submit button. As you can see, the List was returned and each object has its new updated data.





This simple example shows how easy it is to use EditorTemplates in MVC, and how to easily pass a List and get edits back.

Enjoy!

No comments:

Post a Comment