0
我剛剛開始使用MVC,JSON,AJAX等,並且作爲一個側面項目一直試圖創建一個數據即儀表板。MVC5不通過JSON屬性名稱來查看
今天我跟着就如何簡單的數據表通過從SQL的JSON我的看法本指南:http://techfunda.com/howto/292/list-records-using-json
它主要的工作:在JsonResult從我的控制器來通過,幷包含值但不屬性名稱。 這會導致問題,因爲我在處理要在JavaScript中顯示的數據時引用屬性名稱。
這裏的SQL數據:
這裏是我的模型:
public partial class vw_Dash_ChartData : IEnumerable<object>
{
[Key]
[JsonProperty(PropertyName = "Classification")]
public string Classification { get; set; }
[JsonProperty(PropertyName = "Count")]
public int Count { get; set; }
public IEnumerator<object> GetEnumerator()
{
yield return Classification;
yield return Count;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
(你會發現我試圖手動設置[JsonProperty(...)]
東西...它沒有幫助)
這裏是我的JsonResult:
public JsonResult ChartDataJson()
{
var data = new List<vw_Dash_ChartData>();
data = db.vw_Dash_ChartDatas.ToList();
var jsonData = Json(data, JsonRequestBehavior.AllowGet);
return jsonData;
}
(最初我從我的DbContext
直接發送數據,但後來認爲它可能有助於使用我的vw_Dash_ChartData
模型。這沒有什麼區別)。
我的看法如下所示:
@{
ViewBag.Title = "Charts";
AjaxOptions options = new AjaxOptions
{
//Confirm = "Are you sure?",
LoadingElementId = "divLoading",
OnSuccess = "processDataMethod",
Url = Url.Action("ChartDataJson")
};
}
<script type="text/javascript">
function processDataMethod(data) {
var output = $("#dataZone");
output.empty();
for (var i = 0; i < data.length; i++) {
var chartData = data[i];
output.append("<tr><td>" + chartData.Classification + "</td><td>" + chartData.Count + "</td></tr>");
}
}
</script>
<div>
<table>
<thead>
<tr>
<th>Classification</th>
<th>Count</th>
</tr>
</thead>
<tbody id="dataZone">
</tbody>
</table>
</div>
@using (Ajax.BeginForm(options))
{
<div id="divLoading" style="color: red; font-size: larger;">
Loading...
</div>
<div>
<button type="submit" id="btnClicky" >Clicky</button>
</div>
}
<script>
$("#btnClicky").trigger("click");
</script>
當我加載頁面,這就是我得到:
,這是在瀏覽器開發商所示的JSON對象工具;
任何提示/想法感激地接受!另外,如果我正在做任何愚蠢的事情,請讓我知道,因爲我想學習這個東西的最佳做法。
是的!這樣可行!雖然問題:我是否應該將JsonRequestBehaviour.AllowGet追加到jsonData聲明的末尾?它有什麼不同? – Hoppertron
這主要用於安全。請在此處查看:http://stackoverflow.com/a/8464685/1551178 – joaoruimartins
您可以投票並將答案標記爲正確嗎? – joaoruimartins