Using Html.Editor To Create Empty For New Entries

Using the EditorFor template is a very nice feature of ASP.Net MVC 3, but is it possible to get an editor to render an unvisited template that allows you to create posts?

Or is there any other way to do this?

The methods I'm trying to do are as follows:

@Html.EditorFor(model => model) @Html.EditorFor(x => new List<Business.ViewModel.Affiliate.Contact>()) @Html.EditorFor(new List<Business.ViewModel.Affiliate.Contact>()) @Html.EditorFor(new Business.ViewModel.Affiliate.Contact()) 

The first one obviously works, but the following ones (which show what I'm trying to do) do not work with the following error:

  Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. 

The model in question:

  IEnumerable<Business.ViewModel.Affiliate.Contact> 
+8
templates asp.net-mvc-3
source share
2 answers

The responsibility of the dispatcher is to prepare the presentation model that will be passed to the presentation. Therefore, if you need, for example, to initialize the view model using 5 empty contact lines, you can do this simply in your controller:

 public ActionResult Index() { var model = new MyViewModel { // Add 5 empty contacts Contacts = Enumerable.Range(1, 5).Select(x => new Contact()).ToList() }; return View(model); } 

and, in your opinion, use the EditorFor helper, as usual:

 @model MyViewModel ... @Html.EditorFor(x => x.Contacts) 

This will create an appropriate editor template for each of the 5 elements that we have added to the Contacts collection.

+6
source share

If your question is not related to AJAX, then I would design the ViewModel as follows:

 class MyList { public List<MyRow> Rows {get;set;} public MyRow NewRow {get;set;} } 

Then you can easily add the empty editor associated with the NewRow property. And in the controller, you add NewRow to the rows on subsequent calls.

0
source share

All Articles