【问题标题】:MVC: When returning from the controller on Ajax call, the result is undefinedMVC:在 Ajax 调用上从控制器返回时,结果未定义
【发布时间】:2018-08-02 14:53:36
【问题描述】:

单击 Kendo 按钮并返回模型时,我正在对控制器进行 Ajax 调用:

@(Html.Kendo().Button()
                    .Name("btnSubmit")
                    .HtmlAttributes(new { type = "button" })
                    .Icon("rotate")
                    .Content("View Details"))

<script>
    $("#btnSubmit").click(function () {
        $.ajax({

            url: "/MyController/MyMethod/",
            type: 'post',
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                window.location.href = "@Url.Action("RedirectToView", "MyController", new { myModel = "data" })".replace("data", result);
            }
        })
    });
</script>

控制器的方法返回模型:

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult MyMethod()
{
    var reportDate = Session["FileDate"] == null ? DateTime.Now : Convert.ToDateTime(Session["FileDate"].ToString());
    var myModel = new MyModel();
    myModel.ColOfData = myModel.GetColOfData(reportDate);
    return Json(myModel, JsonRequestBehavior.AllowGet);
}

当我调试 Ajax 函数时,结果未定义。结果应该分配给 MyModel,因为我将模型返回到 Ajax 函数。我需要将该结果传递给控制器​​中的另一个方法,该方法将返回包含网格的Partial View

public ActionResult RedirectToView(MyModel myModel)
{
    return PartialView("_MyPartialView", myModel);
}

我做错了什么?

【问题讨论】:

  • 您到底为什么要进行 ajax 调用,然后使用 location.href 进行重定向(ajax 的全部意义在于保持在同一页面上,而您所做的只是降低性能。只是在 POST 方法中进行正常的提交和重定向)

标签: c# asp.net-mvc model-view-controller kendo-asp.net-mvc asp.net-mvc-ajax


【解决方案1】:

您的问题与剑道无关。

你必须从你的控制器返回一个像这样的 json 对象

return Json(new {result=myModel});

在您的 ajax 结果中,您将拥有整个模型。

在您提供的代码之后,恐怕您无法在 GET 的 url 中传递整个模型。

你可能会这样传递模型 ID

 window.location.href = "@Url.Action("RedirectToView", "MyController", new { id= "modelId" })".replace("modelId", result.Id);

让你的动作变成那样

public ActionResult RedirectToView(string id){
    // Get the model data you want .....
    return PartialView("_MyPartialView", myModel);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    相关资源
    最近更新 更多