gpt4 book ai didi

javascript - ASP.NET MVC - jQuery POST 方法为 null

转载 作者:行者123 更新时间:2023-11-28 05:38:23 25 4
gpt4 key购买 nike

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

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

这是<div>我在其中注入(inject) 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(这将被注入(inject)到上面的 <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调用 Controller 中的方法。但是,我遇到了以下问题。

  1. 当执行以下代码时,$('#FormCreateSample').serialize()预计返回 PartialView 的模型为空,其中所有属性均为空。

      $(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. 因为我在 Controller 中的操作方法有 [ValidateAntiForgeryToken]注释,上面的脚本抛出异常“ token 不存在...”。为了解决这个问题,我更新了代码并添加了以下代码行。

     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 方法的问题是,它通过了 null我的操作方法中的值 sampleData范围。下面是我 Controller 中的操作方法。

    [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 .

enter image description here

最佳答案

您需要在 ajax 调用的消息 header 中添加 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");
}
});

关于javascript - ASP.NET MVC - jQuery POST 方法为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39159307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com