我正为网格生成以下hml:
<form method="POST" action="home/Edit">
<table>
<thead>
<tr>
<th> Level </th>
<th> Cost </th>
<th> Test </th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type='text' name="Prize[0].Level" value='1' /> </td>
<td> <input type='text' name="Prize[0].Cost" value='$1.00' /> </td>
<td> <input type='text' name="Prize[0].Properties['Test'].Name" value='Passed' /> </td>
</tr>
<tr>
<td> <input type='text' name="Prize[1].Level" value='2' /> </td>
<td> <input type='text' name="Prize[1].Cost" value='$2.00' /> </td>
<td> <input type='text' name="Prize[1].Properties['Test'].Name" value='Failed' /> </td>
</tr>
</tbody>
</table>
<input type="submit"/>
</form>
我的家庭控制器有一个方法:
[HttpPost]
public ActionResult Edit(PrizelevelsModel model) { ... }
模型定义如下:
public class PrizelevelsModel
{
public PrizeLevel[] Prize { get; set; }
}
public class PrizeLevel
{
public readonly Dictionary<string, PrizeLevelProperty> Properties = new Dictionary<string, PrizeLevelProperty>();
public int Level { get; set; }
public decimal Cost { get; set; }
}
public class PrizeLevelProperty
{
public int Ordinal { get; set; }
public string Name { get; set; }
public object Value { get; set; }
}
当我点击提交时,MVC用Prize [2]膨胀我的模型,数组中的每个Prizelevel都有正确的Level和Cost,但是Properties字典有0个元素。如何让MVC添加到每个Prize的Properties字典中,使用“Test”键和一个新的PrizeLevelProperty元素,并在每个Prize的表单中设置名称?
换句话说,当我调试我的控制器方法时,我想看看:
model.Prize[0].Level == 1 // this works ok
model.Prize[0].Cost == "$1.00" // and so does this
model.Prize[0].Properties["Test"].Name" == "Passed" // but not this, instead model.Prize[0].Properties.Count == 0
答案 0 :(得分:0)
这篇文章非常符合您的要求:http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
MVC 3中的默认模型绑定器将绑定字典,您可以在其中指定项目的键和值,因此在您的情况下,它将如下所示:
<form method="POST" action="home/Edit">
<table>
<thead>
<tr>
<th> Level </th>
<th> Cost </th>
<th> Test </th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type='text' name="Prize[0].Level" value='1' /> </td>
<td> <input type='text' name="Prize[0].Cost" value='$1.00' /> </td>
<td>
<input type='text' name="Prize[0].Properties[0].Key" value='Test' />
<input type='text' name="Prize[0].Properties[0].Value.Name" value='Passed' />
</td>
</tr>
<tr>
<td> <input type='text' name="Prize[1].Level" value='2' /> </td>
<td> <input type='text' name="Prize[1].Cost" value='$2.00' /> </td>
<td>
<input type='text' name="Prize[0].Properties[0].Key" value='Test' />
<input type='text' name="Prize[0].Properties[0].Value.Name" value='Failed' />
</td>
</tr>
</tbody>
</table>
<input type="submit"/>
</form>
虽然你可能会隐藏密钥,具体取决于你想要实现的目的。