我正在尝试使用$.getJSON
函数传递多个参数。为此,我创建了一个DTO
类,定义如下。
public class MyDTO
{
public string IncludeProperties {get; set;}
public Dictionary<string,string[]> Predicate {get; set;}
}
这是我的网络API功能:
[HttpGet]
[Route("FindAll")]
public IEnumerable <Hotel> FindAll([FromUri] MyDTO predicateDTO) {
return DataStore.FindAll <Hotel> (predicateDTO.IncludeProperties, PredicateHelper.ConvertStringToLambda <Hotel> (predicateDTO.Predicate));
}
var uri = '/api/Hotel/FindAll';
var predicate = {
"HotelName": ["HOtel", "==", ""],
"PaymentStatus": ["True", "==", "AND"]
}
var data = {
IncludeProperties: ["HotelDetails", "HotelDetails.HotelMainPhotos"],
Predicate: predicate
}
busyIndicatorVisibility(true);
$('#ModalOtel .modal-body').find(".media").remove();
$.getJSON(uri, {
predicateDTO: data
}).done( //TODO something)
当我调用我的函数IncludeProperties
时,项目Predicate
属性为null
。
如何将Dictionary<string,string[]>
作为参数传递?
答案 0 :(得分:0)
我会尝试向您展示从解决方案开始的想法。
您需要像这样更新您的MyDTO模型:
public class Predicate
{
public string[] HotelName { get; set; } // In javascript can hold: ["HOtel", "==", ""]
public string[] PaymentStatus { get; set; }
}
public class MyDTO
{
public string[] IncludeProperties { get; set; }
public Predicate predicate { get; set; }
}
在你的jQuery函数中,你需要为$ .ajax()替换$ .getJSON,如下所示:
var predicate = {
"HotelName": ["HOtel", "==", ""],
"PaymentStatus": ["True", "==", "AND"]
};
var data = {
IncludeProperties: ["HotelDetails", "HotelDetails.HotelMainPhotos"],
Predicate: predicate
};
$.ajax(
{
url: uri,
type: "POST",
data: JSON.stringify(data), // To convert javascript objects in json strings.
dataType: "json",
contentType: "application/json; charset=utf-8", // To send json objects to the web api controller.
beforeSend: function ()
{
console.log("Wait a minute...");
},
success: function (response)
{
console.log(response);
}
});
$ .ajax()函数将使用以下格式发送您的json数据:
{
"IncludeProperties": [
"HotelDetails",
"HotelDetails.HotelMainPhotos"
],
"Predicate": {
"HotelName": [
"HOtel",
"==",
""
],
"PaymentStatus": [
"True",
"==",
"AND"
]
}
}
在您的网络API控制器中,尝试更改为:
public string FindAll(MyDTO predicateDTO) // This contains all model with submodels.
{
string result = "";
// You can have access to predicateDTO instance with the current data;
// predicateDTO.predicate.HotelName...
return result;
}
我希望这会对你有所帮助。
答案 1 :(得分:0)
我改变了方法。
[HttpGet]
[Route("FindAll")]
public IEnumerable<Hotel> FindAll(string[] IncludeProperties, string Predicate)
{
Dictionary<string,string[]> predicateAsDictionary = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(predicateString)
return DataStore.FindAll<Hotel>(IncludeProperties, predicateAsDictionary);
}
getJson
方法不会将jquery中定义的var predicate
对象转换为Dictionary
但是当我使用JSON.stringify(predicate)
发送此对象时,我可以反序列化该字符串到Dictionary