Problem with updating model on AJAX "POST"

I am trying to update my model without refreshing the page. I am using the built-in wysiwyg editor that I have in many places on my page. The editor can be placed anywhere on the page, it can look like this:

<div id="1" class="click2edit">@Model.Header</div>

<div id="2" class="click2edit">@Model.Content</div>

      

Each editor div

has a SaveButton that goes into this jquery, ajax below. What it does: When I click on the save button, for example <div id="1" class="click2edit">@Model.Header</div>

It sends the div id and its content (in this case @Model.Header

). And all mine@model

$('.click2edit').click(function () {
    var modelDataJson = '@Html.Raw(Json.Encode(Model))';
    $(this).note({ focus: true });
    var activeId = (this.id);
    activeId = activeId.replace(/ /g, '');
    $(this).note({
        oninit: function () {
            $('#saveFileBtn').click(function (event) {
                $('#previewBtn').click(),
                $.ajax({
                    url: '/Home/SaveContent',
                    type: 'POST',
                    data: {
                        model: modelDataJson,
                        activeId: activeId,
                        contentToUpdate: $("div#" + activeId).html()
                    },
                    dataType: 'json',
                    success: function (data) {
                        alert("sucess");
                    },
                    error: function () {
                        alert("error");
                    }
                });
                $('.click2edit').destroy();
            });
        }
    });
});

      

Then in my mvc controller, it puts the new content in the right place and stores it in db. This can be done by replacing the entire old model with the new one posted from the view:

[ValidateInput(false)]
public void SaveContent(string model, string activeId, string contentToUpdate)
{
    //my logic to save to db is here...
}

      

The problem is this: My model in my shaver mode is not updating. Everything works fine if I just save one of my editor files. But when I try to save another one before I refresh my page it doesn't refresh. This is because my razor-views @model

are still retaining their old values. So the only value that gets updated is the last one I keep. Can I somehow update my @model views without refreshing the whole page?

EDIT: Now Iv'e changed my success function to look like this:

success: function (data) {
    $("#1").text(data.Header);
},

      

But the model value of this is not updated. the data I am sending back from the success function is my model as Json.

<div id="1" class="click2edit">@Model.Header</div>

      

+3


source to share


1 answer


Here is a summary of our chat:

An MVC model is an instance that contains server-generated data that is used to control rendering and presentation of data for a view. The stateless HTTP status indicates that the only time you can access this data on the server side is when the view is in the process of rendering. After rendering it, it is completely in the hands of the browser and any data present in the server object is freed from memory.

After that, you can no longer use Razor server-side syntax @if

or @model

to access model data (the model as it existed when the page was rendered no longer exists). Instead, you have to work with DOM and JavaScript objects to update the look and feel of the page (while storing the data using server-side Ajax). Without making a full page post, your only option is to use client side code (JavaScript) to control what the user sees (hence the name: view) so that what they see matches the changes that occurred after the AJAX POST.

I created a Gist here that demonstrates these concepts: https://gist.github.com/xDaevax/f5e192c03f6a2bfc2cdb

Essentially, for your controller, you need code similar to the following:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AjaxMvcTest.Controllers {
    public class HomeController : Controller {
        //
        // GET: /Home/


        public ActionResult Index() {
            HomeModel model = new HomeModel();
            model.Header = "Default Header";
            model.Content = "People assume that time is a strict progression of cause to effect, but actually, from a non-linear, non-subjective viewpoint, it more like a big ball of wibbly-wobbly... timey-wimey... stuff.";
            return View(model);
        }

        [ValidateInput(false)]
        public JsonResult SaveContent(UpdateDataModel updateRequest) {
            //Do some stuff
            HomeModel newModel = new HomeModel();
            newModel.Content = updateRequest.Content;
            newModel.Header = updateRequest.Header;

            return Json(newModel);
        }

    }
}

      

Here is the view to be used with the above controller:

@model HomeModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<div id="1" class="click2edit">@Model.Header</div>
<br />
<div id="2" class="click2edit">@Model.Content</div>
<br />
Header:&nbsp;&nbsp; <input type="text" name="HeaderInput" id="HeaderInput" value="@Model.Header" />
<br />
Content: <textarea name="ContentInput" id="ContentInput">@Model.Content</textarea>
<br />
<input type="button" id="saveFileBtn" value="Save" />

<script type="text/javascript">
    $(function () {

        $("#saveFileBtn").click(function (e) {
            $.ajax({
                url: '/Home/SaveContent',
                type: 'POST',
                data: getFormData(),
                dataType: 'json',
                success: function (data) {
                    $("#1").text(data.Header);
                    $("#2").text(data.Content);
                    $("#HeaderInput").val(data.Header);
                    $("#ContentInput").val(data.Content);
                },
                error: function () {
                    alert("error");
                }
            });
        });
    });

    function getFormData() {
    //Convert the form data to a javascript object
        var dataToSubmit = {
            Header: $("#HeaderInput").val(),
            Content: $("#ContentInput").val(),
            TimeStamp: new Date(),
            Id: 1
       };

       return dataToSubmit;
    }
</script>

      

So you can see that the client code (JavaScript) is responsible for updating the view in the success

method callback ajax

after the controller has done the work and the method is getFormData()

used to convert the form values ​​into a JavaScript object that the MVC binder can read and transform into a model on .NET server side. If you don't want to do it manually, you can use the JQuery method serialize

to serialize the entire form, provided the form values ​​match your server model.

+4


source







All Articles