MVC:在Ajax调用中从控制器返回时,结果不确定

时间:2018-08-02 14:53:36

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

单击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);
}

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您的问题与剑道无关。

您必须从控制器中返回这样的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);
}