我正在尝试简化将数据从 WebMethod 层返回到客户端的过程,并在 Dictionary<string,string>
中表示来自客户端的参数集。做这样的事情:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static override ResultObject<List<PatientInfo>> GetResults(Dictionary<string, string> query)
{
ResultObject<List<PatientInfo>> resultObject = null;
if (!query.ContainsKey("finValue"))
{
resultObject = new ResultObject<List<PatientInfo>>("Missing finValue parameter from the query");
}
string finValue = query["finValue"];
if(finValue == null)
{
resultObject = new ResultObject<List<PatientInfo>>("Missing finValue parameter value from the query");
}
var patientData = GetPatientsByFin(finValue);
resultObject = new ResultObject<List<PatientInfo>>(patientData);
return resultObject;
}
}
我的问题是:如何传递和反序列化 Dictionary 参数?
最佳答案
要传递字典,您必须使用 WebService。
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class TestService : System.Web.Services.WebService
{
[WebMethod]
public String PostBack(Dictionary<string, string> values)
{
//You should have your values now...
return "Got it!";
}
}
然后当你想调用它时,你可以传递这样的东西。不确定您是否使用 jQuery,但这里有一个使用 jQuery 的 ajax 方法的示例。
var valueObject = {};
valueObject['key1'] = "value1";
valueObject['secondKey'] = "secondValue";
valueObject['keyThree'] = "3rdValue";
$.ajax({
url: 'TestService.asmx/PostBack',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ values: valueObject }),
success: function (data) {
alert(data);
},
error: function (jqXHR) {
console.log(jqXHR);
}
});
关于.net - 调用 WebMethod,传递 Dictionary<string, string> 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17373452/