Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First thing in the jQuery the proper way to set a value of an input is to use</p> <pre><code>$("#Str").val(@Model.Str); </code></pre> <p>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. </p> <pre><code>[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); } </code></pre> <p>Next I would place your html inputs in a so you can have jquery serialize your model for you and then you can change your jquery post code to be:</p> <pre><code>function changeButtonClicked() { var url = '@Url.Action("ChangeTheValue", "Test1")'; $.post(url, $('form').serialize(), function (view) { $("#Str").val(view); }); } </code></pre> <p>All the serialize is doing is encoding the inputs in your form into a string and if everything is named properly aps.net will bind that back to your model.</p> <p>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:</p> <pre><code>[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); } } </code></pre> <p>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.</p> <p>I hope this is helps you out and is what you were looking for.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload