![](/img/trans.png)
[英]Ajax post to ASP.net MVC controller - object properties are null
[英]ASP.NET MVC - jQuery POST method is null
我正在调用PartialView
并将其从另一个PartialView
注入到<div>
,以使用Boostrap Modal
使其成为弹出模式。 到目前为止,我的Boostrap Modal正在按预期显示但不按预期运行。 以下是我在Boostrap Modal中的目标。
这是<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">×</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
来调用控制器中的方法。 但是,我遇到了以下问题。
当执行下面的代码时,期望返回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"); } }); } }); } }); }); });
由于我在控制器中的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.