javascript 如何正确呈现 AJAX POST MVC 4 的返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15714194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:49:00  来源:igfitidea点击:

How to properly render the return of AJAX POST MVC 4

javascriptasp.net-mvcjqueryasp.net-mvc-4

提问by mvcNewbie

I'm using MVC 4 and I am trying to send a post request and I am getting a successful return from my controller with the resulting view in HTML form, but I'm not sure what to do with it at that point.

我正在使用 MVC 4 并且我正在尝试发送一个 post 请求,并且我从我的控制器成功返回了 HTML 形式的结果视图,但我不确定在这一点上如何处理它。

JS

JS

$("form").submit(function (e) {
    e.preventDefault();
    if ($(this).valid()) {
        $.ajax({
            url: submitUrl, type: "POST", traditional: true,
            data: { EventName: 'Name of event'},
            success: function(data){
                $("#content").html(data);
            }
        })
    }
});

my controller

我的控制器

[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
    if(ModelState.IsValid)
    {
        return RedirectToAction("Index");
    }
    else
    {
        return View(model);
    }
}

So you can see that my controller either returns a View or a RedirectToAction. In the success callback of my ajax call I am doing the following: $("#content").html(data); But nothing seems to happen. Can someone help push me in the right direction of properly handling the return of the controller action.

所以你可以看到我的控制器要么返回一个视图,要么返回一个 RedirectToAction。在我的 ajax 调用的成功回调中,我正在执行以下操作: $("#content").html(data); 但似乎什么都没有发生。有人可以帮助我朝着正确的方向正确处理控制器动作的返回。

Thank you so much!

太感谢了!

回答by Jasen

If I understand correctly, you have a Create Event form on your page and you want to send an AJAX request to create a new event. Then you want to replace a section in your page #contentwith the results of the CreateEventaction.

如果我理解正确,您的页面上有一个“创建事件”表单,并且您想发送 AJAX 请求以创建新事件。然后,您想#content用操作的结果替换页面中的某个部分CreateEvent

It looks like your AJAX is set up correctly so that CreateEventreturns a successful response. I think you're now confused about the response. You have several options but let's choose two.

看起来您的 AJAX 设置正确,因此CreateEvent返回成功的响应。我想你现在对回应感到困惑。您有多种选择,但让我们选择两个。

JSON response

JSON 响应

[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
    if(ModelState.IsValid)
    {
        var event = service.CreateEvent(model); // however you create an event
        return Json(event);
    }
    else
    {
        // model is not valid so return to original form
        return View("Index", model);
    }
    ...

Now you need to generate html markup from the JSON and insert it into #content.

现在您需要从 JSON 生成 html 标记并将其插入到#content.

$.ajax({
    url: submitUrl, type: "POST", traditional: true,
    data: { EventName: 'Name of event'},
    success: function(data){
        var obj = JSON.Parse(data);
        var html; // build html with the obj containing server result
        $("#content").html(html);
    }
})

or HTML fragment

HTML 片段

Instead of returning a full page with a Layoutdefined we'll return just a PartialViewwithout Layoutand all the headand scripttags.

Layout我们不会返回带有定义的完整页面,我们将只返回一个PartialView没有Layout和所有的headscript标签。

[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
    if(ModelState.IsValid)
    {
        var event = service.CreateEvent(model); // however you create an event
        return PartialView("CreateEventResult", event);
    }
    else
    {
        // model is not valid so return to original form
        return View("Index", model);
    }
}

Now make a new partial view CreateEventResult.cshtml(Razor)

现在创建一个新的局部视图CreateEventResult.cshtml(Razor)

@model Namespace.EventModelResult
@ {
    Layout = null;
}
<div>
    <!-- this stuff inserted into #content -->
    @Model.Date
    ...
</div>

and the javascript is unchanged

并且 javascript 没有变化

$.ajax({
    url: submitUrl, type: "POST", traditional: true,
    data: { EventName: 'Name of event'},
    success: function(data){
        $("#content").html(data);
    }
})

Edit:If your Event creation fails for any reason after you have validated the input, you'll have to decide how you want to respond. One option is to add a response status to the object you return and just display that instead of the newly created Event.

编辑:如果您在验证输入后因任何原因创建事件失败,您必须决定要如何响应。一种选择是向您返回的对象添加响应状态,并仅显示该状态而不是新创建的事件。