views:

39

answers:

1

Suppose I have passed in a viewmodel with a PERSON record with multiple addresses

I'm looking to write a view something like this (simplified)

<% foreach (var addr in Model.PERSON.ADDRESSES) { %>
    <li>
        <%: Html.TextBoxFor(m => addr.Add1)%>
    </li>
<% } %>

Which appears to display as expected, however, each generated Textbox has the same ID and Name attributes, and not surprisingly, the controller code fails to make any updates to the model.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection) 
{
    MyViewModel viewmodel = GenerateViewModel(id);
    try
    {
        UpdateModel(viewmodel);
        _MyRepository.Save();
        return View(viewmodel);
    }
    catch
    {
        return View(viewmodel);
    }
}

I'm guessing I'm going about this the wrong way: any clues would be greatly appreciated!

A: 

You could use editor templates.

Controller:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.PERSON = FetchPerson();
    return View(model);
}

[HttpPost]
public ActionResult Edit(MyViewModel model) 
{
    _MyRepository.Save(model);
    return View(model);
}

View:

<ul>
    <%: Html.EditorFor(x => x.PERSON.ADDRESSES) %>
</ul>

Editor template for address (~/Shared/Views/EditorTemplates/ADDRESS.ascx):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.ADDRESS>" %>

<li>
    Street: <%: Html.EditorFor(x => x.Street) %>
</li>
Darin Dimitrov
This is nearly right. I think your first ActionResult should have been Edit() ? With that I get controls rendered with plausible names - PERSON.ADDRESSES[1].Street but when trying to save I get an error System.InvalidOperationException was unhandled by user code Message=The EntityCollection has already been initialized. The InitializeRelatedCollection method should only be called to initialize a new EntityCollection during deserialization of an object graph. (from myModel.Designer.cs EntityCollection<ADDRESS>ADDRESSES setter)
Andiih
My error is also addressed here stackoverflow.com/questions/1064998/… I have a similar viewmodel with a graph of entities, and some dropdown lists. Sadly none of the solutions posted seem to work (for me or the OP)
Andiih