Jan 14, 2016

EditorTemplates in MVC

Before today, I just knew the concept of Editor Templates in MVC but had never used them in an application.

So today, I was stuck up with a scenario where there was a registration page containing a common area of the form(which can be used in other places) e.g. address.
My models were structured something similar to what is shown below.




Coming from WebForms background(and not knowing how to use Editor Templates), I created a View for the Register action and a PartialView for the Address section. It was something as shown below.



The Get action method was working fine but the Post action method was not able to fetch me the values from the PartialView. It was just returning null, no matter what I did.


Then, while going through a post, I realised that Editor Templates was just the solution that I was looking for.

So, let's go through how to create Editor Templates in this scenario.

1. Our pain point here is the AddressDetails coming as null. What is it's type?? Address. So, create a file with the name Address.cshtml inside Shared\EditorTemplates folder. Create the folder EditorTemplates, if not present already.


2. Now, for the best part. In the Register view, replace the Html.RenderPartial, with EditorFor, as shown below.


That's all, aaaand it works.


MVC model binding takes care of all this heavy-lifting for us behind-the-scenes. It's so beautiful and elegant. :)

I hope this helps you as well.



3 comments:

  1. Liked it. Have never used it. Will be useful.

    ReplyDelete
  2. Just to reiterate though - the partial view for address is not required at all while using editor templates right? It picks up directly if you populate it using controller - correct?

    ReplyDelete
    Replies
    1. Yes, partial view is not required, we just need to place a Address.cshtml in EditorTemplates folder. MVC is based on convetions, just like we create controllers with the suffix Controller, by placing a Address.cshtml in EditorTemplates folder MVC recognizes it.

      Delete