首页 > 解决方案 > 使用 ajax 更新数据库后重新加载页面

问题描述

所以我需要在使用 ajax 请求向控制器发送数据后重新加载我的页面。控制器将其保存到数据库中,然后重新加载的页面应该具有更新的内容:

[控制器]

public class ProcessingController : Controller
{
    ManageProcessing runManager = new ManageProcessing();

    [Authorize] 
    public ActionResult Index()
    {
        RunModel rm = new RunModel
        {
            RunList = runManager.GetRunModelList()
        };
        return View(rm);
    }
    [HttpPost]
    public ActionResult SaveReprocessData(Run runPost)
    {
        runManager.SaveToDataBase(runPost);

        return RedirectToAction("Index", "Processing");
    }
}

[看法]

 function Reprocess() {
        var checkedID = '#' + document.querySelector('input[name="select"]:checked').value;
        var line = $(checkedID)[0].children;
        var obj = {};

        obj.ID = line[0].textContent;
        obj.EndDate = line[1].textContent;
        obj.ProcessedDate = line[2].textContent;

        $.ajax({
            type: "POST",
            url: '@Url.Action("SaveReprocessData", "Processing")',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(obj),
            dataType: "json",
            success: function (result) {    
                window.location.reload();
                alert("updated licenses");
            },
            error: function (ex) {
                alert(ex);
                console.log("we have failed");
            }
        });
    }

SaveReprocessData 应该返回什么来接收视图上的新视图?以及如何使用该回报?

标签: jquery.netajaxmodel-view-controller

解决方案


我同意托比亚斯。您通过尝试重新加载页面来破坏使用 ajax 的全部目的,但您的解决方案将只是更改SaveReprocessData方法的返回类型并返回一个新的数据列表

[HttpPost]
public RunModel SaveReprocessData(Run runPost)
{
    runManager.SaveToDataBase(runPost);

    return runManager.GetRunModelList();
}

此外,除非在执行 ajax POST 请求后客户端需要在服务器端生成值,否则您可以避免对数据库的额外调用。您只需要将您的 javascript 代码更新为这样的内容

$.ajax({
            type: "POST",
            url: '@Url.Action("SaveReprocessData", "Processing")',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(obj),
            dataType: "json",
            success: function (result) {    
               // window.location.reload();
               // alert("updated licenses");
                 reloadView(obj); 
            },
            error: function (ex) {
                alert(ex);
                console.log("we have failed");
            }
        });

推荐阅读