Modelmetadata附加值始终为空MVC4

时间:2013-08-02 11:32:05

标签: asp.net-mvc-4

我的模型中有以下属性:

    [Required]
    [UIHint("DropDownList")]
    [AdditionalMetadata("Source", "Party.Organization.Caption")]
    public int PartyId { get; set; }

我正在尝试在视图中获取其他元数据值,如下所示:

    object s = ViewData.ModelMetadata.AdditionalValues["Source"];

但它总是返回0。

不确定,为什么,有人可以建议吗?

完整视图:

 @model IEnumerable<object>
 @using System.Reflection;
 @using r2d2Web.Extensions;
 @using d2Utils.Extensions.d2Type;
 @using d2Utils.Reflection;
 @using System.Collections;

 @{
Type mdlType = Model.First().GetType();
PropertyInfo keyProp = mdlType.GetKeyProperty();
IEnumerable<PropertyInfo> props = mdlType.EditorProps();
Hashtable parties = (Hashtable)ViewData["Parties"];
Hashtable partyroles = (Hashtable)ViewData["Partyroles"];
 }
 <div class="grid">

  <table>
    <thead>
        <tr>
            @foreach (var prop in props)
            {
            <th>@prop.Name</th>
            }
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var obj in Model)
        {               
        <tr>
            @foreach (var prop in props)
            {
                if (prop.Name == "PartyId")
                {
                 object s = ViewData.ModelMetadata.AdditionalValues["Source"];
                 <td>@(obj.GetValForProp<string>(s.ToString()))</td>      
                }
                else if (prop.Name == "PartyRoleTypeId")
                {
                     <td>@partyroles[obj.GetValForProp<int>(prop.Name)]</td>                
                }
                else
                {
                    <td>@(obj.GetValForProp<string>(prop.Name))</td>                
                }
            }
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = obj.GetValForProp<int>(keyProp.Name) }) |
            </td>
        </tr>
        }
    </tbody>
</table>
 </div>
 <div id="my-dialog"></div>

1 个答案:

答案 0 :(得分:1)

您没有指定获取其他元数据的字段。试着这样做:

@ViewData.ModelMetadata.Properties.FirstOrDefault(n => n.PropertyName == "PartyId").AdditionalValues["Source"]

如果你有一个强类型的视图模型,其类型包含PartyId,那么更好的选择就是使用

 @ModelMetadata.FromLambdaExpression(x => x.PartyId, ViewData).AdditionalValues["Source"]