Asp MVC3 Custom EditorTemplate for collections (empty or not)

After long searches, stackoverflowing (?) And reading the blog, I still cannot completely solve the problem. I hope this community of experts can come to the rescue!

Given: A company class with an ICollection field (a Company can have many addresses). Each address has several simple string fields.

Short version:

I want the user to be able to add any number of addresses to the company. First I want to show one set of Address text boxes, and then the "Add another address" button. Javascript is not a problem, rather part of mvc. If unclear, the functionality should be similar to this: http://www.mdelrosso.com/sheepit/index.php?lng=en_GB&sec=demo3

I need to use the MVC function EditorForModel (), which means that the whole configuration should go in the editor templates.

Status so far:

  • Created ViewModel for company editing page (CompanyViewModel)
  • Added [UIHint ("Addresses")] to field ICollection Addresses {get; set; }
  • Created Address EditorTemplate

In the Addresses Editor, when adding a new company, the model passed in Null (there are no surprises). How to create an editor for an additional address? I tried several incarnations (using Razor):

@Html.EditorFor(m => new Address()); 

but cannot produce anything even remotely. (The exact line above gives the error "Templates can only be used with access to a field, access to properties, an index of a one-dimensional array, or one-parameter expressions of a custom indexer.")

Thanks for any pointers!

/ Victor

+4
source share
1 answer

This is a flaw in existing APIs. One way to do this is to have a child action responsible for creating the insert form

In your controller:

 [ChildActionOnly] public ActionResult AddAddress() { return View(new Address()); // pass an instance so view works } 

Add New View AddAddress.cshtml

 @model Address @Html.EditorForModel() 

Then in the editor template use

 @Html.Action("AddAddress") 
+4
source

All Articles