![](/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.