Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating View with Model changes via Ajax Post - MVC3
    text
    copied!<p>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.</p> <p>Here's the overview:</p> <p><strong>MODEL</strong></p> <pre><code>public class MyModel { public int Integer { get; set; } public string Str { get; set; } } </code></pre> <p><strong>CONTROLLER</strong></p> <pre><code> 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); } </code></pre> <p><strong>VIEW</strong></p> <pre><code> @model Test_Telerik_MVC.Models.MyModel @using Test_Telerik_MVC.Models @{ ViewBag.Title = "Test1"; Layout = "~/Views/Shared/_Layout.cshtml"; } &lt;h2&gt; Test1&lt;/h2&gt; @if (false) { &lt;script src="~/Scripts/jquery-1.4.4.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="~/Scripts/jquery-ui.min.js" type="text/javascript"&gt;&lt;/script&gt; } &lt;h2&gt; ViewPage1 &lt;/h2&gt; &lt;div&gt; &lt;input type="button" onclick="changeButtonClicked()" id="changeButton" value="Click Me!" /&gt; &lt;input type="text" value="@Model.Str" class="txt" id="str" name="Str"/&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; function changeButtonClicked() { var url = '@Url.Action("ChangeTheValue", "Test1")'; var data = '@Model'; $.post(url, data, function (view) { $("#Str").value = '@Model.Str'; }); } &lt;/script&gt; </code></pre> <p>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. </p> <p>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.</p> <p>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?</p> <p>Thanks</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