Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating View with Model changes via Ajax Post - MVC3

Tags:

I am trying to use an Ajax (I think) call to update my model value and then have that new value reflected in the view. I am just using this for testing purposes for the moment.

Here's the overview:

MODEL

public class MyModel {     public int Integer { get; set; }     public string Str { get; set; } } 

CONTROLLER

    public ActionResult Index()     {         var m = new MyModel();         return View("Test1", m);     }      [HttpPost]     public ActionResult ChangeTheValue(MyModel model)     {         var m = new MyModel();         m.Str = model.Str;         m.Str = m.Str + " Changed! ";         m.Integer++;          return View("Test1", m);      } 

VIEW

  @model Test_Telerik_MVC.Models.MyModel @using Test_Telerik_MVC.Models @{     ViewBag.Title = "Test1";     Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>     Test1</h2> @if (false) {     <script src="~/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>     <script src="~/Scripts/jquery-ui.min.js" type="text/javascript"></script> } <h2>     ViewPage1 </h2>  <div>     <input type="button" onclick="changeButtonClicked()" id="changeButton" value="Click Me!" />     <input type="text" value="@Model.Str" class="txt" id="str" name="Str"/>     <div></div> </div>  <script type="text/javascript">      function changeButtonClicked() {         var url = '@Url.Action("ChangeTheValue", "Test1")';         var data = '@Model';         $.post(url, data, function (view) {             $("#Str").value = '@Model.Str';         });     }  </script> 

Basically the view renders a button with a textbox. My sole aim is to simply display the value of my model (Str property) in the textbox.

I have tried various combinations of the changeButtonClicked() function to no avail. Test1 is the name of my controller. What I don't understand is when I debug it, the controller action fires and sets my values correctly. If I place a breakpoint on the "@Model.Str" section of the input tag, it shows me that my @Model.Str is equal to Changed! which is correct. However, as soon as my success function fires in the javascript, the value reverts back to it's original value.

I can make it work by changing the input type to submit and wrapping it in a @Html.BeginForm() section but I am wondering if/how to do it like this? Or is a Submit the only way to accomplish it?

Thanks

like image 439
Jason Avatar asked Oct 14 '11 05:10

Jason


People also ask

How to update a model in the view in Ajax call?

Step 1: Create the basic structure of your project, View and View Model. Step 2: Create Controller add Action which will return the JSON result, My Controller is as below. Note I have added action which return the JSON result. Step 3: Include jQuery and AJAX in your project.

How do I update view model?

When you click the submit button, the HttpPost action method above will be executed and the value of model. FavoriteColor will be what you select in the dropdownlist. After that you can use that value to update your database. and you can get the person id in model.

How reload page after Ajax call in MVC?

The . reload() method can be triggered either explicitly (with a button click) or automatically. You can also use the . reload() method inside an Ajax success callback function and this is very simple.

Can we use Ajax in MVC?

The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features. To enable the unobtrusive AJAX support in the MVC application, open the Web.


1 Answers

First thing in the jQuery the proper way to set a value of an input is to use:

$("#Str").val(@Model.Str); 

Next we'll look at the controller. In the POST action result you are returning the entire View in your AJAX call. That means all the HTML, script references, and JavaScript are being returned in your jQuery post request. Since all you are trying to update is the value of the input named Str, I would just return that value as JSON and nothing else.

[HttpPost] public ActionResult ChangeTheValue(MyModel model) {     var m = new MyModel();     m.Str = model.Str;     m.Str = m.Str + " Changed! ";     m.Integer++;      return Json(m.Str);  } 

Next I would place your HTML inputs in a <form> so you can have jQuery serialize your model for you and then you can change your jQuery post code to be:

function changeButtonClicked() {     var url = '@Url.Action("ChangeTheValue", "Test1")';     $.post(url, $('form').serialize(), function (view) {         $("#Str").val(view);     }); } 

All the serialization is doing is encoding the inputs in your form into a string and if everything is named properly ASP.NET will bind that back to your model.

If you need to have your route handle both AJAX calls and full requests you could use ASP.NET's IsAjaxRequest function to test the request and return different results depending on if the request is AJAX or not. You would do something like this in your controller:

[HttpPost] public ActionResult ChangeTheValue(MyModel model) {     var m = new MyModel();     m.Str = model.Str;     m.Str = m.Str + " Changed! ";     m.Integer++;      if (Request.IsAjaxRequest) {         return Json(m.Str);     }     else {         return View("Test1", m);     } } 

In the ActionResult above you are doing everything you did before, but now are testing the request type and if it's AJAX you return a JSON result of your string value. If the request was not from an AJAX call then the full View (HTML, scripts, etc) are returned to be displayed in the browser.

I hope this is helps you out and is what you were looking for.

like image 128
ajrawson Avatar answered Nov 09 '22 23:11

ajrawson