MVC3 receiving the new model data after submit

2019-09-14 02:04发布

问题:

I can't update the view model.

I have view called: Overview

I have this in the view's controller:

public ActionResult Overview()
{
    var evo = new OverviewViewObject
    {
        MvcGridModel = new MvcGrid(),  
        SingleExportData = new SingleExportData()
    };

    return View(evo);
}

Then i have Save The buttons calles:

$.ajax({
         url: saveUrl,
         cache: false,
         type: "post",
         data: JSON.stringify({  Name:  myName  }),
          contentType: "application/json",
          success: function (data) { .. }...

the saveUrl goes to:

[HttpPost]
public ActionResult Save(MyDataType saveData)
{
    //todo save logic here

    var mvcGridModel =  GetGridData();
    var evo = new ExportDataOverviewViewObject
    {
        MvcGridModel = mvcGridModel ?? new MvcGrid(),
        SaveData = new MyDataType()
    };

    return View("Overview", evo);
}

And it goes fine in the Save, and it get fine the data in the saveData object, and it doens't return any error till the end, but when after the return it shows the view,the data is not displayed there anymore.

Could you please help me?

回答1:

A couple of remarks:

  • If the Save button is a form submit button or an anchor make sure that you return false from the callback after the $.ajax call to ensure that the default action is not executed
  • In your controller action you are returning a full view (return View()) instead of a partial view which is what is more common for controller actions that are being invoked with AJAX.

So to recap:

$('#saveButton').click(function() {
    $.ajax({
        url: saveUrl,
        cache: false,
        type: 'POST',
        data: JSON.stringify({ Name: myName }),
        contentType: 'application/json',
        success: function (data) { 
            // do something with the data => refresh some
            // portion of your DOM
            $('#someDivId').html(data);
        }
    });
    return false;
});

and your controller action:

[HttpPost]
public ActionResult Save(MyDataType saveData)
{        
    //todo save logic here

    var mvcGridModel = GetGridData();
    var evo = new ExportDataOverviewViewObject
    {
        MvcGridModel = mvcGridModel ?? new MvcGrid(),
        SaveData = new MyDataType()
    };
    return PartialView("Overview", evo);
}