我需要使用json数据发送到我的Controller字符串,但是这个字符串的参数可能会被更改,所以我必须创建不是Json原语,而是使用看起来像这样的json数据的字符串:
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);
}
});
当我使用Json原语时很明显,但是我不知道如何在Controller中接受这个字符串?
这是Controller(请注意,json参数应该接受json字符串,但我不确定它是否正确)。
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);
}
答案 0 :(得分:0)
如果您只是将var json
传递给其他服务而不是自行处理:
var json = "{" + destfrom + from + ", " + destto + to + ", 'DepartureDate':" + $("#departure").val() + ", 'ReturnDate':" + $("#return").val() + "}";
$.ajax({
url: "/Home/GetFlights",
data: { json: json },
type: "post",
success: function (result) { }
});
而且你不需要改变你的行动
public async Task<JsonResult> GetFlights(string json, DateTime DepartureDate, DateTime ReturnDate)
{
var prices = await tr.GetPrices(User.Identity.Name, psw, json, DepartureDate, ReturnDate);
...
}
另请注意,单引号无效JSON。