在我的MVC應用程序的數據,這是我的模型:發送使用jQuery/AJAX MVC的控制器
public class Student
{
public string StudentId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
我的.cshtml是這樣的:
@using (Ajax.BeginForm(null, "TestAjaxBeginForm", null , null))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.StudentId, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.StudentId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StudentId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" onclick="GetData()"/>
</div>
</div>
</div>
}
我使用jQuery發送的控制器數據來自.cshtml文件。
<script>
function GetData()
{
debugger;
var Student = [
{
'StudentId': $('#StudentId').val(),
'Name': $('#Name').val(),
'Address': $('#Address').val()
}
];
Student = JSON.stringify({ 'Student': Student });
$.ajax({
type: "POST",
url: "/Student/GetData/",
dataType: "json",
contentType: "application/json",
data: Student,
processData: true,
success: function (data) {
alert("Hi");
//alert(data);
},
error: function (xhr, ajaxOptions, error) {
alert(xhr.status);
alert("Error: " + xhr.responseText);
//alert(error);
}
});
}
</script>
我的控制器:
[HttpPost]
public ActionResult GetData(Student Student)
{
var StudentId = Student.StudentId.ToString();
var StudentName = Student.Name.ToString();
var Address = Student.Address.ToString();
return Json(JsonRequestBehavior.AllowGet);
}
我我得到的JScript函數中的表單數據,但裏面控制器StudentId,StudentName和地址(的GetData)值顯示爲空。 任何幫助將被感謝接受。
感謝 帕塔
你的方法接受一個單一的對象,而不是一個集合,以便其'var Student = {...};'(無方括號)。但是你可以通過使用'data:$('form')。serialize()''並且刪除'contentType'選項來簡化所有這些。但是你想在這裏做什麼 - 你有'Ajax.BeginForm()'和'$ .ajax()',所以你做了2個Ajax調用。 –