【发布时间】:2020-07-22 02:50:30
【问题描述】:
我可以通过使用 Ajax-Call 将元素添加到 Code-Behind 但我无法反序列化 asp.net中Code-Behind中的元素
这是我的 Ajax 调用
function responseData2() {
var demodata = [];
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val() + "\n";
alert("The Names are: " + data);
demodata.push({
var_name_data: data,
});
});
$.ajax({
url: "url",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + demodata + "'}",
success: function (data) {
data = $.parseJSON(data.d);
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
我的代码隐藏:如何在代码隐藏中检索元素:我的 ajax 调用以单个字符串值“[object Object]”返回数据
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object Details4(string selectedJobSheet)
{
try
{
string constr = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("select customer_id,first_name from jobsheetDetails", con))
{
string _data = "";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
_data = JsonConvert.SerializeObject(ds.Tables[0]);
}
return _data;
}
}
}
catch (Exception)
{
throw;
}
}
如何反序列化元素以及如何将元素绑定到列表或数组
【问题讨论】:
-
使用 JSON 库,例如 NewtonSoft.JSON 并将 JSON 反序列化为模型。但是你应该注意你只发送一个对象,所以你根本不需要列表或数组
-
在 .NET Core 3.0 或更高版本中,有
System.Text.Json命名空间来序列化和反序列化 json(作为 Newtonsoft.JSON 的替代品),它在 Web 应用程序中默认启用 -
如果添加 Rows like
JsonConvert.SerializeObject(ds.Tables[0].Rows),结果是否相同? -
这能回答你的问题吗? Convert datatable to JSON in C#
-
代码中的 try/catch 有什么意义?
标签: javascript c# jquery asp.net jquery-ui