【发布时间】:2014-10-14 03:36:45
【问题描述】:
我有一个页面,每当状态更改时,我都会在其中执行 Ajax Post。我想更新模型以反映新的变化。例如,如果州从 AZ 更改为 NY,我想将州更改为 NY,学生的名字更改为 Jenny。但是,表格没有更新。我做错了什么?
历史:以前,我将信息保存在数据库中,每次有人访问该页面时,我都必须多次调用数据库。然后,我将它切换到会话变量,我必须在其中创建几个变量并维护这些变量。我正在寻找一种更好的方法。我认为进行 Ajax 发布并能够在成功发布后更新表单会更干净,至少在我看来是这样。
这是我的代码示例:
@model School.Models.NewStudents
@{
ViewBag.Title = "New Students";
}
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function changeState() {
var Students= $('#NewStudent').serialize();
$.ajax({
url: '@Url.Action("SetNewStudents", "Student")',
type: 'POST',
datatype:'json',
data: Students,
cache: false,
// contentType: 'application/text;charset=UTF-8',
success: function (e) {
//Here is where I am updating the form with the new NewStudents Object.
$('#NewStudent').html(e.NewStudents);
}
</script>
@using (Html.BeginForm("SetNewStudents", "Student", FormMethod.Post, new {id = "NewStudent" }))
{
@Html.ValidationSummary(true)
@Html.LabelFor(model => model.FirstName, "FirstName:")
<br/>
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
@Html.DropDownList("Name", null, "Choose State", new { onchange = "changeState()" })
}
[HttpPost]
public JsonResult SetNewStudents(NewStudents NewStudents)
{
NewStudents.FirstName = "Jenny"; //I changed the first name To Jenny now. However, the form is not updated to show Jenny.
return Json(new { success =true, NewStudents = NewStudents });
}
更新:我更改了返回 JSON 结果而不是视图的方法。
这是 URL 编码中的请求: FirstName=sdfsd&Name=15
这是 JSON 响应: 返回结果:{"ok":true,"NewStudent":{"FirstName":"Jenny", "StateID":15}}
【问题讨论】:
-
e.NewStudents 包含什么?尝试将
console.log(e.NewStudents)添加到您的 Ajaxsuccess()方法中。此外,启动 Chrome/Firefox/.. 控制台以查看 Ajax 请求是否实际返回2xx代码。否则不会调用success()方法。 -
您需要序列化您的表单并从您的操作中返回一个 JSON 对象。有关一些方法,请参阅此帖子:stackoverflow.com/questions/5980389/…
-
我看了e.NewStudents,它是一个对象。
-
我这样做是因为一个州内有多个位置。例如,如果您选择 NY,您将在其中选择一个位置的另一个下拉列表。使用 Ajax 帖子,我不会丢失用户在表单中键入的任何值。此外,我没有创建会话变量或将该信息保存在数据库中。它是持久的。
标签: javascript jquery asp.net asp.net-mvc-3 asp.net-ajax