user11974227
user11974227

Reputation:

how to bind a MVC model with ajax call?

I want to bind an MVC model with ajax call and want to call a JS function using onclick event in partial view but there is an error bulkconfirm() is not defined as well as how I can bind the model with ajax call basically this is my partial view in which when user click confirm button then this click bulkconfrim() function should be called? Thanks

@model Manual_Tag_Entry.ViewModel.ModelAccessor



<div class="modal-header">
    <h3 class="modal-title" id="exampleModalLabel">Do you want to update following information?</h3>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<form id="test">
    <table class="table table-striped table-bordered" width="80%">
        <thead>
            <tr>
                <th>Tag Name</th>
                <th>Tag Old Value</th>
                <th>Tag New Value</th>
            </tr>
        </thead>
        <tbody>

            @if (Model.updatedDatas != null)
            {
                foreach (var item in Model.updatedDatas)
                {
                    <tr>
                        <td>
                            @item.TagName
                        </td>
                        <td>
                            @item.OldTagValue
                        </td>
                        <td>
                            @item.NewTagValue
                        </td>
                    </tr>
                }
            }


        </tbody>
    </table>
</form>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary" onclick="BulkConfirm()">Confirm Update</button>
</div>


@section script{
    <script>
    function BulkConfirm()
    {
        debugger;
        var [email protected];
    $.ajax({
    type: 'POST', //GET
    url: '@Url.Action("BulkUpdateConfirmation", "Home")',
    data: data
    });
    $("#myModal").modal('hide')
    }
    </script>
}

Upvotes: 0

Views: 776

Answers (2)

C Murphy
C Murphy

Reputation: 57

To add onto A. Nadjar's answer, in your view, change the for each loop in your view to a for loop and use the HTML Helpers DisplayFor and the HiddenFor for each property in your list.

for (var i = 0; i < Model.updatedDatas.Count; i++)
{
    <tr>
         <td>
              @Html.DisplayFor(modelitem => modelitem.updatedDatas[i].TagName)
              @Html.HiddenFor(modelitem => modelitem.updatedDatas[i].TagName)
         </td>
    </tr>
}

Upvotes: 0

A. Nadjar
A. Nadjar

Reputation: 2543

You need to convert your view model into a Javascript object, using Html Helpers:

var obj = @Html.Raw(Json.Encode(Model));

Here you can see the exact solution: https://stackoverflow.com/a/16361388/4687359

Upvotes: 1

Related Questions