Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 - edit items dynamically added to model collection in jquery dialog

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?

like image 559
user759550 Avatar asked May 18 '11 18:05

user759550


1 Answers

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.

like image 78
Philter Avatar answered Oct 03 '22 09:10

Philter