【发布时间】:2017-04-01 16:19:22
【问题描述】:
在我的 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 函数中获取表单数据,但在 Controller(GetData) 中 StudentId、StudentName 和地址的值显示为空。 任何帮助都将被接受。
谢谢 帕萨
【问题讨论】:
-
你的方法接受一个对象,而不是一个集合,所以它的
var Student = { ... };(没有方括号)。但是您可以通过使用data: $('form').serialize(),并删除contentType选项来简化这一切。但是你想在这里做什么 - 你有Ajax.BeginForm()和$.ajax()所以你做了 2 个 ajax 调用。
标签: jquery .net json ajax asp.net-mvc