I have a page where I am doing an Ajax Post whenever the state is changed. I'd like to update the model to reflect the new changes. For example, if the state is changed from AZ to NY,I'd like to change the state to NY and student First Name to Jenny. However, the Form is not being updated. What did I do wrong?
History: Previously, I saved the information in a database, and I had to make several calls to the database every time someone access the page. Then, I switched it to session variables where I had to create several variables and maintain those variables. I am looking for a better way of doing it. I thought doing the Ajax post and being able to update the form upon a successful post will be much cleaner, at least in my view.
Here is a sample of my code:
@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 });
}
Update: I changed the method to return a JSON Result instead of a View.
This is the request in URL Encoded: FirstName=sdfsd&Name=15
This is the JSON Response: return result :{"ok":true,"NewStudent":{"FirstName":"Jenny", "StateID":15}}