1

我正在为网格生成以下 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>

我的 Home 控制器有一个方法:

[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 将键为“Test”的元素添加到每个奖品的属性字典中,值是新的 PrizeLevelProperty,其名称与每个奖品的表单中设置的名称相同?

换句话说,当我调试我的控制器方法时,我想看到:

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
4

1 回答 1

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>

尽管您可能会根据您想要实现的内容/方式来隐藏密钥。

于 2013-03-15T01:45:46.880 回答