简体   繁体   中英

MVC: When returning from the controller on Ajax call, the result is undefined

I'm making an Ajax call to the controller when clicking on a Kendo button and return the model:

@(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>

The controller's method returns the model:

[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);
}

When I debug my Ajax function, result is undefined. The result should be assigned to MyModel, since I'm returning the model back to an Ajax function. I need to pass that result to another method in the controller that would return my Partial View containing the Grid:

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

What am I doing wrong?

Your problem isn't related to kendo.

From your controller you have to return a json object like this

return Json(new {result=myModel});

And in your ajax result you will have your entire model.

After that from the code you provided I am afraid you can't pass your entire model in the url of your GET.

You could probably pass the model Id like that

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

And make your action something like that

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM