return url.action as json object mvc

2019-08-09 04:57发布

问题:

My Controller method returns Json object which has url formed as shown below :

return Json(new { url = Url.Action("ShowContact", "Customer", new { vm = contactVM }) }, JsonRequestBehavior.AllowGet);

In the ajax call's success code, I want to assign this url to window.location.href so I can redirect to view as per url formed. But return value of ajax call shows plain text value for route value passed as part of url.

Hence, I'm not getting whatever route value I want to pass to the redirect action method of my controller.

So what are the options I have in order to pass my route value which is complex c# object including collections? Is there any better approach to achieve what I want to do?

Thanks,

回答1:

Try piecing it together:

return Json(
    new
    {
        url = Url.Action("ShowContact", "Customer"),
        vm = contactVM
    },
    JsonRequestBehavior.AllowGet);

Then on the client:

var url = result.url + '?vm=' + JSON.stringify(result.vm);

Granted, I've never tested this.



回答2:

You can pass the url string directly instead of 'Url.Action()'. Something like this:

string url = "Customer/ShowContact?vm=" + contactVM;

return Json(url , JsonRequestBehavior.AllowGet);