繁体   English   中英

ASP.NET MVC - jQuery POST方法为null

[英]ASP.NET MVC - jQuery POST method is null

我正在调用PartialView并将其从另一个PartialView注入到<div> ,以使用Boostrap Modal使其成为弹出模式。 到目前为止,我的Boostrap Modal正在按预期显示但不按预期运行。 以下是我在Boostrap Modal中的目标。

  1. 制作Boostrap模式 - 好的
  2. 在Boostrap Modal上添加验证 - 确定
  3. 发送我的模态的值以保存在数据库中 - 不行

这是<div> ,我在其中注入PartialView并使其成为模态

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Create Sample</h4>
        </div>
        <div class="modal-body">
            <div id="modalBodyContainer">

            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="btnCreateSample">Create</button>
        </div>
    </div>
</div>

PartialView显示为Boostrap Modal(这将在上面的<div>注入)

@model WebSensoryMvc.Models.SampleData

 @using (Html.BeginForm("Create", "SessionData", FormMethod.Post, new { id = "FormCreateSample", name = "FormCreateSample" }))
 {
@Html.AntiForgeryToken()

<div class="container">
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.GroupNo, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GroupNo, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GroupNo, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.MaterialID, "Material", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("MaterialID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.MaterialID, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.SampleCode, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.SampleCode, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.SampleCode, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.BatchCode, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.BatchCode, new { htmlAttributes = new { @class = "form-control text-uppercase" } })
                    @Html.ValidationMessageFor(model => model.BatchCode, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.SizeID, "Size", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("SizeID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.SizeID, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.AgeID, "Age", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("AgeID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.AgeID, "", new { @class = "text-danger" })
                </div>
            </div>

        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.TemperatureID, "Temperature", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("TemperatureID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.TemperatureID, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.PackagingTypeID, "Packaging Type", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("PackagingTypeID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.PackagingTypeID, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.Spike, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.Spike)
                        @Html.ValidationMessageFor(model => model.Spike, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.SampleType, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.SampleType, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.SampleType, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>

        <div class="row">
            <div class="form-group">
                @Html.LabelFor(model => model.Remarks, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Remarks, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
    </div>
</div>
 }

目前,我很难调试在数据库中保存模态值。 我正在使用ajax来调用控制器中的方法。 但是,我遇到了以下问题。

  1. 当执行下面的代码时,期望返回PartialView模型的$('#FormCreateSample').serialize()为空,其中所有属性都为null。

      $(document).ready(function () { $("#btnModal").on('click', function () { var url = "/SessionData/Create"; $.ajax({ url: url, type: 'GET', success: function (data) { $('#modalBodyContainer').html(data) $('#myModal').modal('show'); $("#btnCreateSample").off().on('click', function () { var form = $('form'); form.data('validator', null); $.validator.unobtrusive.parse(form); if ($('form').valid()) { $.ajax({ url: "/SessionData/Create", type: "POST", data: $('#FormCreateSample').serialize(), success: function () { alert("POST success"); }, error: function () { alert("POST error"); } }); } }); } }); }); }); 
  2. 由于我在控制器中的action方法有[ValidateAntiForgeryToken]注释,上面的脚本抛出异常“令牌不存在......” 为了解决这个问题,我更新了我的代码并添加了下面的代码行。

      var token = $('input[name="__RequestVerificationToken"]').val(); $.ajax({ url: "/SessionData/Create", type: "POST", data: { $('#FormCreateSample').serialize(), __RequestVerificationToken: token }, success: function () { alert("POST success"); }, error: function () { alert("POST error"); } }); 

#2方法的问题是,它在我的action方法sampleData参数中传递null值。 以下是我的控制器中的动作方法。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public void Create(SampleData sampleData)
    {
        if (ModelState.IsValid)
        {
            sampleData.SessionID = Convert.ToInt32(TempData["CurrentSessionId"]);

            db.SampleDatas.Add(sampleData);
            db.SaveChanges();

            RedirectToAction("List", "SessionData");
        }

    }

任何人都知道为什么$("FormCreateSample").serialize()null 或者它可能找不到表单id FormCreateSample

TIA

更新1使用第一个答案后,模型现在传递给方法,但所有属性仍为null

在此输入图像描述

您需要在ajax调用的消息头中添加AntiForgeryToken:

var token = $('input[name="__RequestVerificationToken"]').val();
var tokenadr = $('form[action="/SessionData/Create"] input[name="__RequestVerificationToken"]').val(); 

var headers = {};
var headersadr = {};
headers['__RequestVerificationToken'] = token;
headersadr['__RequestVerificationToken'] = tokenadr;

 $.ajax({
 url: "/SessionData/Create",
 type: "POST",
 headers: headersadr,
 data: "__RequestVerificationToken=" + token + "" + $('form[action="/SessionData/Create"]').serialize(),
success: function () {
   alert("POST success");
},
error: function () {
    alert("POST error");
}
});

尝试改变

.serialize()

.serializeArray()
var token = $('input[name="__RequestVerificationToken"]').val();
  $.ajax({
     url: "/SessionData/Create",
     type: "POST",
     data: { $('#FormCreateSample').serialize(), __RequestVerificationToken: token },
     content-type : 'application/json',
    success: function () {
       alert("POST success");
    },
    error: function () {
        alert("POST error");
    }
 });

添加:content-type:'application / json',

在调试我的场景几天后,我现在找到了我的解决方案。 我没有使用Bootstrap Modal ,而是使用Bootbox 使用Bootbox修复了从验证到保存到数据库的所有问题。

下面是我用来打开模态的脚本。

<script>
$(document).ready(function () {
    $("#modalCreateSample").on('click', function () {
        $.ajax({
            url: "/SessionData/Create",
            type: 'GET',
            success: function (data) {

                bootbox.dialog({
                    title: "Create Session",
                    message: data,
                    buttons: {
                        success: {
                            label: "Save",
                            className: "btn-success",
                            callback: function () {

                                var form = $('#FormCreateSample');
                                form.data('validator', null);
                                $.validator.unobtrusive.parse(form);

                                if ($(form).valid()) {
                                    $.post("/SessionData/Create", $("#FormCreateSample").serialize(), function (data, status) {
                                        if (status == "success") {
                                            // Refresh list of samples

                                            return false;
                                        }
                                    });
                                } else {
                                    return false;
                                }
                            }
                        }
                    }
                });

            },
            error: function (error) {
                bootbox.alert("We encounter problem while retrieving the Sample Code of the selected Session");
            }
        });
    });
});
 </script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM