0

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}}

Josiane Ferice
  • 921
  • 5
  • 15
  • 31
  • 1
    What does e.NewStudents contain? Try adding `console.log(e.NewStudents)` to your Ajax `success()` method. Also, fire up a Chrome/Firefox/.. console to see if the Ajax request actually returns a `2xx` code. Otherwise the `success()` method won't be called. – Bjorn Aug 20 '14 at 17:24
  • You need to serialize your form and return a JSON object from your action. See this post for some approaches: http://stackoverflow.com/questions/5980389/proper-way-to-use-ajax-post-in-jquery-to-pass-model-from-strongly-typed-mvc3-vie – Will Jenkins Aug 20 '14 at 17:34
  • I looked at e.NewStudents, and it is an object. – Josiane Ferice Aug 20 '14 at 17:52
  • I am doing it this way because there are several locations within a state. If you choose NY for example, you will have another drop down populated where you'd have to select a location. Using the Ajax post, I don't lose any of the values that the user typed in the form. In addition, I don't have create session variables or saved that information in the database. It's persistent. – Josiane Ferice Aug 20 '14 at 18:00

1 Answers1

1

In you AJAX success function, you are returning JSON, not html so this line wont work

$('#NewStudent').html(e.NewStudents);

You need to extract the values and then update each element, for example

success: function (e) {
  $('#FirstName').val(e.NewStudent.FirstName);
  $('#StateID').val(e.NewStudent.StateID);
}