我使用json.net来序列化我的DataTable.我将这个json字符串(结果)传递给视图,以便在无序列表中呈现它。但是json格式在结果中被搞乱了。
DataAccess
public static string getClinic()
{
string sproc = "getClinic";
return callProcedure(sproc);
}
public static string callProcedure(string sproc)
{
DataTable ds = null;
try
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnString))
{
SqlCommand cmd = new SqlCommand(sproc, sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
ds = new DataTable();
adapter.Fill(ds);
string json = JsonConvert.SerializeObject(ds);
return json;
}
}
catch (Exception ex)
{
throw ex;
}
}控制器
public ActionResult Index()
{
QueryModel qModel = new QueryModel {
tblClinic = new Clinic(),
};
return View("Index", qModel);
}视图
<ul>
@foreach (var p in Model.tblClinic.clinic){
<li>@p</li>
}
</ul>但我的数据被搞砸了:
[
{
"
c
o
d
e
"
:
0
,
"
n
a
m
e
"
:
"
A"
}
,
{
...
}我希望是:
code: 0, name: A
code: 1, name: B..。
在循环之前,我需要先反序列化json对象吗?
更多信息:我的模型
public class QueryModel
{
public Clinic tblClinic { get; set; }
}我的领域
public class Clinic
{
public string clinic { get; set; }
public Clinic() {
this.clinic = Data.getClinic();
}
}发布于 2014-03-11 09:40:17
在循环之前,我需要先反序列化json对象吗?
是的,很明显。您需要先对json对象进行反序列化,然后再循环。否则,循环遍历string只会在每一步产生一个char。
类中的反序列化可能类似于:
public class RootObject // you have to set the class name
{
public int code { get; set; }
public string name { get; set; }
}然后,在视图中,您可以循环如下:
<ul>
@foreach (RootObject p in JsonConvert.DeserializeObject<List<RootObject>>(Model.tblClinic.clinic))
{
<li>code: @p.code, name: @p.name</li>
}
</ul>https://stackoverflow.com/questions/22308574
复制相似问题