ASP.NET MVC 3 - edit items dynamically added to mo

2019-02-05 05:17发布

问题:

I'm new to MVC, so I wasn't sure what the best approach would be here.

I have a view model that contains several collections like this:

public class MainViewModel{      
    public List<AViewModel> A { get; set; }
    public List<BViewModel> B {get; set; }
    ...}

I'm using Steve Sanderson's approach here to dynamically add items to a collection, and it's working fine as long as the child items are editable on the main view.

The problem I'm having is returning a read only list with an edit link that will open the details to edit in a popup dialog.

Since these items may be newly added, I can't use the ID property to return a partial view from the controller. It seems like I'll have to render the editors in a hidden div like this:

    <div class="AEditorRow">
    @using (Html.BeginCollectionItem("A"))
    {                                                                 
        @Html.DisplayFor(l => l.ID)                

        @Html.DisplayFor(l => l.Name)

        @Html.DisplayFor(l => l.Code)

        <a href="#" onclick="$('#detailsPopup').html($(this).parent().find('.ADetails').html() ).dialog()">edit</a> <text>|</text>
        <a href="#" class="deleteRow">delete</a> 

        <div class="ADetails" style="display: none">
 @using (Html.BeginForm("EditA", "Controller"))
            {<fieldset>
                <legend>Location</legend>
                @Html.HiddenFor(model => model.ID)
                <div class="editor-label">
                    @Html.LabelFor(model => model.Code)
                </div>   

Does anyone know of a better way to do this?

回答1:

After working on this issue for a while now I was able to find a walk-through that worked for me.

http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3

I think this is the most applicable technique for accomplishing dynamically added nested collection objects for MVC3. Most of the other suggestions I've found were meant for MVC2 or MVC1, and it seems that every iteration of MVC the best way to accomplish this changes slightly.

Hopefully this works for you.



回答2:

I have the same question. Now looking for solution.

Seems like this resources can help:

http://www.joe-stevens.com/2011/06/06/editing-and-binding-nested-lists-with-asp-net-mvc-2/

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

Model binding nested collections in ASP.NET MVC