如何从子视图访问模型属性的名称

时间:2014-05-09 18:40:58

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5

如果我的模型定义如下:

public class GreaterModel
{
    public IList<LesserModel> MyLesserModelNumber1 {get;set;}
    public IList<LesserModel> MyLesserModelNumber2 {get;set;}
}
public class LesserModel
{
    public string MyString {get;set;}
}

我的观点是这样的:

@model GreaterModel
<h1>My First Editable List</h1>
@Html.EditorAndAdderFor(m=>m.MyLesserModelNumber1)
<h1>My Second Editable List</h1>
@Html.EditorAndAdderFor(m=>m.MyLesserModelNumber2)

EditorAndAdderFor是一种自定义扩展方法,其工作方式与EditorFor类似。它使用以下部分视图添加标记以编辑列表项以及添加新项:(为简洁起见而简化)

@model IEnumerable<object>
/*There's a lot of markup left out here to do with the editing of items (basically uses @Html.EditorForModel()
)*/

/*Then there is input fields to add new items to the list. */
<input type='text' id='addnew-mystring' />

一些JS来处理新条目:

$('#addnew-mystring').focus(function(){
    var value = $(this).val();
    //now I need to add the new value into the list of existing
    //LesserModel items using the correct form name.
    //I.e. "MyLesserModelNumber1[0].MyString"
})

我想知道哪个属性在编辑器模板视图文件中调用我的编辑器模板,这样我就可以为新条目提供正确的HTML表单名称和ID,以便模型绑定工作。所以也许是部分视图中的这样的东西

string name = Html.ViewData.ModelMetadata.PropertyName; 
//should contain "MyLesserModelNumber1", 
//but currently is null

1 个答案:

答案 0 :(得分:0)

我同意大卫的建议。 如果您需要为不同的属性使用完全不同的html,请为每个属性使用不同的模型和视图。 如果您需要相同的视图,并且只取决于属性的轻微更改,您应该在LesserModel中具有区分两者的属性。