[英]ASP.NET MVC 3 + Serializing a collection displayed into <table>
我的ViewModel包含一些對象(IEnumerable)的集合。 集合的項目在標簽的行上顯示。 當我提交表單時,它會觸發提交jQuery函數進行自我驗證。 我需要從顯示的表中獲取值並將其轉換為對象。
看一下這個:
//
// the table to display my collection content
<div id="publications">
Items to publish:
<table>
<thead><tr>
<td></td>
<td>Item</td>
</tr></thead>
<tbody>
@{
for (int counter = 0; counter < Model.Publications.Count; ++counter)
{
<tr>
<td>
@Html.HiddenFor(m => Model.Publications[counter].ID)
@Html.CheckBoxFor(m => Model.Publications[counter].Selected)
</td>
<td>
@Html.HiddenFor(m => Model.Publications[counter].ItemID)
@Html.DisplayTextFor(m => Model.Publications[counter].ItemDescription)
</td>
</tr>
}
}
</tbody>
</table>
</div>
//
// The Publication ViewModel
public class PublicationViewModel {
public string ID { get; set; }
public bool Selected { get; set; }
public string ItemID { get; set; }
public string ItemDescription { get; set; }
}
//
// The main ViewModel
public class MainViewModel {
public string ID { get; set; }
public string Name { get; set; }
public IEnumerable<PublicationViewModel> Publications { get; set; }
}
疑問是如何使用jQuery將表轉換為序列化對象。 十分感謝大家!
將您的代碼放入<form>
並使用Jquery serialize 。
<form id="publications">
Items to publish:
<table>
<thead><tr>
<td></td>
<td>Item</td>
</tr></thead>
<tbody>
@for (int counter = 0; counter < Model.Publications.Count; ++counter)
{
<tr>
<td>
@Html.HiddenFor(m => Model.Publications[counter].ID)
@Html.CheckBoxFor(m => Model.Publications[counter].Selected)
</td>
<td>
@Html.HiddenFor(m => Model.Publications[counter].ItemID)
@Html.DisplayTextFor(m => Model.Publications[counter].ItemDescription)
</td>
</tr>
}
</tbody>
</table>
</form>
和你的jQuery腳本:
$('form').submit(function() {
alert($(this).serialize());
return false;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.