【发布时间】:2014-09-17 19:31:23
【问题描述】:
我有一个 .aspx 页面,我们在运行时将 UserControls 动态加载到该页面中。每个用户控件都有某种文本框或组合或其他一些控件。这一切都很好。当我们在用户按下搜索时从控件中读取值时,我们不能直接从后面的 C# 代码中执行此操作,因为页面不知道它们在那里。我的解决方案是使用 JQuery 读取值并进行 ajax 调用,我可以在其中设置会话变量中的值以供用户进入下一页时使用。我在使用 JSON 时遇到了问题。 我不断收到错误:
{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":"
我使用 .each 找到所有控件并获取 JSon 调用的值:
function SaveFields() {
var data = [];
//get Search field criteria
$('[id^=Search_ucField_]').each(function (index, value) {
var field = $(this);
var id = $(this).attr('id').split("_")[2];
var fieldValue = $(this).val();
if (field.is('input')) {
var item = {};
item['FieldID'] = id;
item['Criteria'] = fieldValue;
item['IsActive'] = 1;
item['FieldCategoryID'] = '1';
item['ControlPath'] = '~/Controls/Search/TextBox.aspx';
item['CategoryID'] = 1;
data.push(item);
}
});
$.ajax({
url: '/Ajax/Ajax.aspx/DoSearch',
type: 'POST',
data: JSON.stringify(data),
datatype: 'json',
contentType: 'application/json',
success: function (msg) {
console.log(msg);
},
error: function (xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
}
这是我要反序列化的对象:
[DataContract]
public class SearchFields
{
[DataMember]
public List<SearchField> Field { get; set; }
}
[DataContract]
public class SearchField
{
[DataMember]
public string FieldID { get; set; }
[DataMember]
public bool IsActive { get; set; }
[DataMember]
public string Criteria { get; set; }
[DataMember]
public int FieldCategoryID { get; set; }
[DataMember]
public string ControlPath { get; set; }
}
这里是 WebMethod
[WebMethod]
public static string DoSearch(string Fields)
{
var sf = new SearchFields();
sf = JsonConvert.DeserializeObject<SearchFields>(Fields);
//save into session variable
SVars.NewUISearch.LastSearchFields = sf;
string x;
x = "until this works, this is a static response";
return x;
}
最后,这是一个正在发送的 JSon 示例:
[{"FieldID":"52","getCriteria":"Bobs your uncle","IsActive":1,"FieldCategoryID":"1","ControlPath":"~/Controls/Search/TextBox.aspx"}]
我哪里错了?提前致谢!
【问题讨论】:
-
您可以通过 Ajax 传递整个强类型模型,而不是 DoSearch 接受 JSON 字符串。尝试将此添加到 Ajax 数据参数:
$(#YourForm).serialize()和 DoSearch 将 ViewModel 作为参数 -
@Scott Loveland 如果你这样做,你应该这样做,你需要将字段名称和类型与强类型相匹配。然后 Asp.Net 模型绑定将为您完成所有工作。需要明确的是,您的方法签名将更改为
DoSearch( SearchField field) -
好的,我理解更改方法中的签名,这是有道理的,但我不太明白在哪里添加 $(#myform).serialize()
-
在我从 json 中删除 [] 并更改我的方法中的签名以接受对象后,我终于得到了这个工作。谢谢你们的帮助!
标签: c# jquery asp.net ajax json