asp.net-mvc-4html-helperbegincollectionitem

HtmlBeginCollectionItem Get Current Item


I need:

  1. Acess /Client/Create
  2. Add dynamically Partial Views (/Product/Card) and bind them to Client.Products
  3. In each Partial View when i click in a button open a bootstrap modal windows where i can set Product's information
  4. Close the modal and reflect changes of modal reflect in the Card's Product.

The problem is: how to change product informations in another view(other than Card) and reflect to the product of the card?

@using (Html.BeginCollectionItem("Products"))
{
    @Html.HiddenFor(model => model.ClientID)
    @Html.HiddenFor(model => model.ProductID)


    <div class="card">
        <img class="card-img-top" src="http://macbook.nl/wp-content/themes/macbook/images/png/iphone318x180.png" alt="Grupo Logo">
        <div class="card-block">
            <h4 class="card-title">@Model.Name</h4>
            <p class="card-text">@Model.Desc</p>
            <div class="btn-group">
                <button type ="button" class="btn btn-primary open-modal" data-path="/Product/Edit/@Model.ProductID">Edit</button>
                <button type="button" class="btn btn-primary open-modal" data-path="/Product/Features/@Model.ProductID">Features</button>
            </div>
        </div>
    </div>

}

enter image description here


Solution

  • You can do this is another view (or by dynamically loading another view into a modal. The object has not been created yet, and since you using BeginCollectionItem() to generate new items, any other view you used would not be using the same Guid created by that helper so you would not be able to match up the collection items.

    Instead, include the 'other' properties within the partial, but put them in a hidden element that gets displayed as a modal when you click the buttons.

    The basic structure of the partial for adding/editing a Product would be

    <div class="product">
        @using (Html.BeginCollectionItem("Products"))
        {
            @Html.HiddenFor(m => m.ClientID)
            @Html.HiddenFor(m => m.ProductID)
            <div class="card">
                ....
                <button type ="button" class="btn btn-primary edit">Edit</button>
            </div>
            // Modal for editing additional data
            <div class="modal">
                @Html.TxtBoxFor(m => m.SomeProperty)
                @Html.TxtBoxFor(m => m.AnotherProperty)
                ....
            </div>
        }
    </div>
    

    And then handle the buttons .click() event (using delegation since the partials will be dynamically added to the view) to display the associated modal (assumes you have a <div id="products"> element that is the container for all Products)

    $('#products').on('click', '.edit', function() {
        var modal = $(this).closest('.product').find('.modal');
        modal.show(); // display the modal
    });