Asp MVC3 Custom EditorTemplate for Collections (Empty or Not)
-
10-10-2019 - |
سؤال
After much googling, stackoverflowing (?) and blog-reading I still cant completely solve the issue. Hopefully this experts community can come to the rescue!
Given: A Company class with a field ICollection (A Company can have many addresses). Each adress has a few 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 textboxes and then a "Add one more address" button. The Javascript is no problem, rather the mvc part. If unclear, the functionality should be similair to this: http://www.mdelrosso.com/sheepit/index.php?lng=en_GB&sec=demo3
I need to use the MVC EditorForModel() function, which means all configuration needs to go in editor templates.
Status so far:
- Created ViewModel for the edit company page (CompanyViewModel)
- Added [UIHint("Addresses")] to the field public ICollection Addresses { get; set; }
- Created Addresses EditorTemplate
In the Addresses EditorTemplate, when adding a new Company, the model passed in is Null (no surprises there). How do I create the editor for the extra address? I tried multiple incarnations of (using Razor):
@Html.EditorFor(m => new Address());
but aint able to produce anything even remotely working. (The exact above line gives the error "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.")
Thanks for any pointers!
/Victor
المحلول
This is a shortcoming of the current APIs. One way you could do it is to have a child action that's responsible for generating the insert form
In your controller:
[ChildActionOnly]
public ActionResult AddAddress() {
return View(new Address()); // pass an instance so view works
}
Add a new view AddAddress.cshtml
@model Address
@Html.EditorForModel()
Then in your editor template use
@Html.Action("AddAddress")