我有一个页面,每当状态发生变化时我都在做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 Result而不是View。
这是URL编码的请求: 姓= sdfsd&安培;名称= 15
这是JSON响应: 返回结果:{“ok”:true,“NewStudent”:{“FirstName”:“Jenny”,“StateID”:15}}
答案 0 :(得分:1)
在你的AJAX成功函数中,你返回的是JSON,而不是html,所以这行不能正常工作
$('#NewStudent').html(e.NewStudents);
您需要提取值然后更新每个元素,例如
success: function (e) {
$('#FirstName').val(e.NewStudent.FirstName);
$('#StateID').val(e.NewStudent.StateID);
}