无法使用Ajax调用将数据发布到控制器的操作方法

时间:2017-08-29 05:51:26

标签: javascript jquery asp.net ajax asp.net-mvc

我正在尝试将Partial View数据发布到服务器,以将输入字段结果保存到数据库,然后返回到相同的(部分视图,作为模式对话框打开)或返回调用模态对话框的父视图。

但由于某些原因,我没有在控制器中获取Action方法的参数(即weldMaster),该参数是从ajax方法调用发送的。

这是我的控制器方法。

    // GET: WeldMasters/Details/5
    public ActionResult Details(int? ids, bool isPartials = false)
    {
        if (ids == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        WeldMaster weldMaster = db.WeldMasters.Find(ids);
        ViewBag.Readonly = false;
        if (weldMaster == null)
        {
            return HttpNotFound();
        }
        if(isPartials)
            return PartialView(weldMaster);
        else
            return View(weldMaster);
    }

    // POST: WeldMasters/Details/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Details**(WeldMaster weldMaster)** 
    //{"The parameter conversion from type 'System.String' to type 'IMCC_PAS.Entities.WeldMaster' failed because no type converter can convert between these types."}
    {
        var success = 0;
        if (ModelState.IsValid)
        {
            success = 1;
            db.Entry(weldMaster).State = EntityState.Modified;
            db.SaveChanges();
            return Json(new { success });
        }
        return Json(new { success });
    }

这是ajax代码

    <script type="text/javascript">
    $(document).ready(function () {
        $(".saveBtn").click(function (e) {
            debugger;
            var token = $('input[name="__RequestVerificationToken"]').val();
            // If I dont pass the token in the `data` parameter of ajax, then action method of controller is not called at all.            
e.preventDefault();
            $.ajax({

                type: "POST",
                url: '@Url.Action("Details", "WeldMasters")',
                data: { __RequestVerificationToken: token, weldMaster: $('#__AjaxAntiForgeryForm').serialize() },
                success: function (result) {
                    alert(result);
                },
                failure: function (response) {
                    alert(result.responseText);
                },
                error: function (response) {
                    alert(result.responseText);
                }
            });
        });
    });
</script>

这是局部视图的模态

@model IMCC_PAS.Entities.WeldMaster

,这是表格

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.id)

        <div class="row">
            <div class="col-md-3 col-sm-12">
                @Html.LabelFor(model => model.weld_no, htmlAttributes: new { @class = "control-label" })
            </div>
            <div class="col-md-3 col-sm-12">
                @Html.LabelFor(model => model.rep_no, htmlAttributes: new { @class = "control-label" })
            </div>
            <div class="col-md-3 col-sm-12">
                @Html.LabelFor(model => model.length, htmlAttributes: new { @class = "control-label" })
            </div>
            <div class="col-md-3 col-sm-12">
                @Html.LabelFor(model => model.normal_size, htmlAttributes: new { @class = "control-label" })
            </div>
        </div>
        <div class="row">
            <div class="col-md-3  col-sm-12">
                @Html.EditorFor(model => model.weld_no, ViewBag.Readonly ? (object)new { htmlAttributes = new { @readonly = "readonly", @class = "form-control" } } : new { htmlAttributes = new { @class = "form-control" } })
            </div>
            <div class="col-md-3  col-sm-12">
                @Html.EditorFor(model => model.rep_no, ViewBag.Readonly ? (object)new { htmlAttributes = new { @readonly = "readonly", @class = "form-control" } } : new { htmlAttributes = new { @class = "form-control" } })
            </div>
            <div class="col-md-3  col-sm-12">
                @Html.EditorFor(model => model.length, ViewBag.Readonly ? (object)new { htmlAttributes = new { @readonly = "readonly", @class = "form-control" } } : new { htmlAttributes = new { @class = "form-control" } })
            </div>
            <div class="col-md-3  col-sm-12">
                @Html.EditorFor(model => model.normal_size, ViewBag.Readonly ? (object)new { htmlAttributes = new { @readonly = "readonly", @class = "form-control" } } : new { htmlAttributes = new { @class = "form-control" } })
            </div>
        </div> 

        <div class="form-group modal-footer">
            <div class="col-md-12">
                <a class="saveBtn" href="javascript:void(0);">Edit</a>
            </div>
        </div>

    </div>
}

编辑:以下是父视图,其中包含用于显示焊接详细信息的选择参数。然后焊接细节以div显示(仅用于读取目的),并且可以在按钮单击时在弹出模式对话框中进行编辑。

    <script>
    $(document).ready(function () {

        ... more code for other dropdowns here

        //When Wled No is changed, reload Weld Details in its respective Partial view
        $("#weldddl").change(function () {

            var parameter = { ids: $("#weldddl").val(), isPartials: true };
            $.ajax({
                url: '/WeldMasters/Details/',
                type: 'GET',
                data: parameter,
                success: function (result) {
                    var div = $('#weldDetails');
                    div.html('');
                    div.html(result);
                }
            });
        });

        $(".editWeldBtn").click(function () {
            //debugger;
            $('#MyModal').empty();
            $('#MyModal').append(GetModalDialog());
            var link = '@Url.Action("Details", "WeldMasters")';
            data = { ids: $("#weldddl").val(), isPartials: true };
            LaunchModalDlg(link, data, "View Weld Master Information", "75%");
        });

    });
</script>

<h4>Index</h4>
<script src="~/Scripts/MyScripts.js"></script>
<p>
    @Html.ActionLink("Create New", "Create") | 
    <a class="editWeldBtn" href="javascript:void(0);">Edit</a>
</p>
<div class="row">
    <div class="col-sm-3">
        @Html.LabelFor(model => model.Discipline, htmlAttributes: new { @class = "control-label col-md-12" })
        <div class="col-md-12">
            @Html.DropDownListFor(model => model.Discipline, (SelectList)ViewBag.disciplines, htmlAttributes: new { @class = "form-control", @id = "disciplineddl" })
            @Html.ValidationMessageFor(model => model.Discipline, "", new { @class = "text-danger" })
        </div>

        @Html.LabelFor(model => model.DrawingNo, htmlAttributes: new { @class = "control-label col-md-12" })
        <div class="col-md-12">
            @Html.DropDownListFor(model => model.DrawingNo, (SelectList)ViewBag.drawings, htmlAttributes: new { @class = "form-control", @id = "drawingddl" })
            @Html.ValidationMessageFor(model => model.DrawingNo, "", new { @class = "text-danger" })
        </div>

        @Html.LabelFor(model => model.ComponentNo, htmlAttributes: new { @class = "control-label col-md-12" })
        <div class="col-md-12">
            @Html.DropDownListFor(model => model.ComponentNo, (SelectList)ViewBag.components, htmlAttributes: new { @class = "form-control", @id = "componentddl" })
            @Html.ValidationMessageFor(model => model.ComponentNo, "", new { @class = "text-danger" })
        </div>

        @Html.LabelFor(model => model.WeldNo, htmlAttributes: new { @class = "control-label col-md-12" })
        <div class="col-md-12">
            @Html.DropDownListFor(model => model.WeldNo, (SelectList)ViewBag.components, htmlAttributes: new { @class = "form-control", @id = "weldddl" })
            @Html.ValidationMessageFor(model => model.WeldNo, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="col-sm-9" id="weldDetails"> <!--This is for showing the partial view for showing weld details-->
    </div>
    <div id="MyModal"></div> <!--This is for pop up modal dialog-->
</div>

1 个答案:

答案 0 :(得分:1)

如果您要对整个表单进行序列化,那么您就不需要明确发送防伪令牌。

使用它:

 data: $('#__AjaxAntiForgeryForm').serialize(),