简体   繁体   中英

How would I send custom string with json data to asp.net mvc controller?

I need to send to my Controller string with json data, but parameters of this string may be changed so I must create not Json primitives but string with json data that look like that:

var from = $("select#optionsfrom").val();
            var destfrom = "'" + $("select#optionfrom option:selected").attr("name") + "':";
            var to = $("select#optionsto").val();
            var destto = "'" + $("select#optionsto option:selected").attr("name") + "':";
            var json = "{" + destfrom + from + ", " + destto + to + ", 'DepartureDate':" + $("#departure").val() + ", 'ReturnDate':" + $("#return").val() + "}";
            $.ajax({
                url: "/Home/GetFlights",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify(json),
                type: "post",
                cache: false,
                success: function (result) {
                    self.prices(result);
                },
                error: function (xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });

It's clear when I'm using Json primitives, but I can't get how should I accept this string in my Controller?

Here is Controller (please note that json parameter should accept json string, but I'm not sure that it is correct way).

public async Task<JsonResult> GetFlights(string json, DateTime DepartureDate, DateTime ReturnDate)
        {
            byte[] stream = HttpServerUtility.UrlTokenDecode(Request.Cookies["psw"].Value);
            byte[] decodedValue = MachineKey.Unprotect(stream, "all");
            var psw = Encoding.UTF8.GetString(decodedValue);
            var prices = await tr.GetPrices(User.Identity.Name, psw, json, DepartureDate, ReturnDate);
            return Json(prices.PriceItems);
        }

If you are just passing var json through to another service and not processing it yourself:

var json = "{" + destfrom + from + ", " + destto + to + ", 'DepartureDate':" + $("#departure").val() + ", 'ReturnDate':" + $("#return").val() + "}";
$.ajax({
    url: "/Home/GetFlights",
    data: { json: json },
    type: "post",
    success: function (result) {  }
});

And you don't need to change your action

public async Task<JsonResult> GetFlights(string json, DateTime DepartureDate, DateTime ReturnDate)
{
    var prices = await tr.GetPrices(User.Identity.Name, psw, json, DepartureDate, ReturnDate);
    ...
}

Also note that the single quotes are not valid JSON.

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