开发者

ASP.NET MVC submitting json array to controller as regular post request (nonajax)

开发者 https://www.devze.com 2022-12-27 19:56 出处:网络
All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax().I\'m submitting some data from a custom user control as a json array.I was wondering if it

All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax(). I'm submitting some data from a custom user control as a json array. I was wondering if it's possible to submit a json array as a regular post request to the server (like a normal form) so the browser renders the page returned.

Controller:

[JsonFilter(Param = "record", JsonDataType = typeof(TitleViewModel))]
public ActionResult SaveTitle(TitleViewModel record)
{
    // save the title.
    return RedirectToAction("Index", new { titleId = tid });
}

Javascript:

function SaveTitle()开发者_JAVA百科 {
    var titledata = GetData();

    $.ajax({
        url: "/Listing/SaveTitle",
        type: "POST",
        data: titledata,
        contentType: "application/json; charset=utf-8",
     });

}

Which is called from a save button. Everything works fine but the browser stays on the page after submitting. I was thinking of returning some kind of custom xml from the server and do javascript redirect but it seems like a very hacky way of doing things. Any help would be greatly appreciated.


This is an old question but this might be useful for anyone finding it --

You could return a JsonResult with your new titleId from the web page

public ActionResult SaveTitle(TitleViewModel record) {
     string tId = //save the title 
     return Json(tId)
}

and then on your ajax request add a success function:

function SaveTitle() {
    var titledata = GetData();

    $.ajax({
        url: "/Listing/SaveTitle",
        type: "POST",
        data: titledata,
        contentType: "application/json; charset=utf-8",
        success: function(data) { window.location = "/Listing/Index?titleId=" + data; }
     });

}

That would redirect the page after a successful ajax request. I just saw that you mentioned this at the end of your post but I think it is an easy and quick way of getting around the issue.


Phil Haack has a nice post discussing this scenario and shows the usage of a custom value provider instead of an action filter.


I don't understand why you would want to post Json if you're wanting to do a full page post. Why not just post normal form variables from the Html form element?

0

精彩评论

暂无评论...
验证码 换一张
取 消