【问题标题】:how to bind a MVC model with ajax call?如何将 MVC 模型与 ajax 调用绑定?
【发布时间】:2020-04-18 22:50:51
【问题描述】:

我想将 MVC 模型与 ajax 调用绑定,并希望在局部视图中使用 onclick 事件调用 JS 函数,但没有定义错误 bulkconfirm() 以及我如何将模型与 ajax 调用绑定这是我的部分视图,当用户单击确认按钮时,应该调用这个 click bulkconfrim() 函数? 谢谢

@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 data=@Model.updatedDatas;
    $.ajax({
    type: 'POST', //GET
    url: '@Url.Action("BulkUpdateConfirmation", "Home")',
    data: data
    });
    $("#myModal").modal('hide')
    }
    </script>
}

【问题讨论】:

    标签: javascript ajax asp.net-mvc


    【解决方案1】:

    您需要将视图模型转换为 Javascript 对象,使用 Html Helpers:

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

    在这里你可以看到确切的解决方案:https://stackoverflow.com/a/16361388/4687359

    【讨论】:

      【解决方案2】:

      要添加到 A. Nadjar 的答案,在您的视图中,将视图中的 for each 循环更改为 for 循环,并为列表中的每个属性使用 HTML Helpers DisplayFor HiddenFor。

      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>
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-24
        • 1970-01-01
        • 2013-12-08
        • 1970-01-01
        • 1970-01-01
        • 2014-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多