Thursday, October 24, 2013

Use a custom editor template when using a partial view to edit data.

Let's say your view is being used to edit some data.  Part of the data being edited appears elsewhere in the app and you might want to reuse it.  For example, an address.  There may be multiple places in your application where you want to have the ability to edit an address.  You might be tempted to just make a partial view and then render it within the parent view by doing something like this:

@Code
    Html.RenderPartial("Address", Model.MyAddressViewModel)
End Code

The problem is that this doesn't bind back to the parent model when the parent form is submitted. Use the Editor helper instead:

@Html.EditorFor(function(m) m.MyAddressViewModel)

Now this will bind. However, the resulting html looks like crap. You can either decorate the crap out of your view model, or just make a custom editor template. All you have to do is make a new folder called EditorTemplates in the Shared folder of your MVC project.  Then put the partial view in this folder.  Make sure you name the view the same as the data type of the object your are creating the editor for.  For example, AddressViewModel.vbhtml.

No comments:

Post a Comment