【问题标题】:How do I get access to the model property's name from a child view如何从子视图访问模型属性的名称
【发布时间】:2014-05-09 18:40:57
【问题描述】:

如果我的模型定义如下:

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

【问题讨论】:

  • 编辑器模板需要知道这一点似乎很奇怪。听起来像一个破损的封装。也许您可以通过向LesserModel 添加一个属性来传达您需要的信息,以指示编辑器视图需要什么?或者将LesserModel 包装在包含此类属性的自定义视图模型中?
  • @David - 感谢您的建议。我已经更新了帖子,所以你可以看到我为什么需要它。我正在尝试模拟 EditorFor 助手,但将其扩展为具有添加功能(因此 EditorAndAdderFor)。为了使模型绑定起作用,我需要属性名称。
  • 从概念上讲,这似乎很奇怪。父模型有两个项目列表。它们会在 UI 中合并成一个列表吗?如果是这种情况,那么在模型中拥有一个列表可能更有意义(即使它只是一个连接两个列表的只读属性)。编辑器模板是显示item 还是list of items?两者之间存在巨大的概念差异,这改变了“添加新”功能所属的位置。
  • 你在这里使用的设计很奇怪。其实我不认为你会继续这样做。无论如何,这个答案将帮助您解决您对stackoverflow.com/a/5514937/105445 的询问
  • @WahidBitar:好吧,也许这是代码中的一个奇怪的设计,但我试图实现的概念是一个非常简单的概念。我想要的只是一个@Html.EditorFor() 调用,它可以编辑列表中的现有项目以及删除和添加新项目。您对此有更好的解决方案吗?

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


【解决方案1】:

我同意大卫的建议。 如果您需要为不同的属性使用完全不同的 html,请为每个属性使用不同的模型和视图。 如果您需要相同的视图并且仅根据属性进行轻微更改,则您应该在 LesserModel 中有一个属性来区分两者。

【讨论】:

  • 谢谢,我对要求不是很清楚。请查看更新后的帖子。我没有对不同的属性完全使用不同的 HTML,我只是将属性名称用于模型绑定。
  • ok。为什么不在 LesserModel 视图中使用 @Html.TextboxFor(Model->MyString) 而不是 标记?这样它就会自动映射
  • 我是。该帖子没有显示我在 LesserModel 的视图中所做的事情。它仅显示 EditorAndAdderFor 扩展使用的部分视图。我无法访问列表中的模型,因此@Html.TextboxFor(m=&gt;m...) 中的模型 m 是 IEnumerable 而不是 LesserModel
  • 好吧,我猜你有理由使用对象而不是 LesserModel。但是,我认为你应该重新考虑你的设计,因为你错过了 MVC 的整个想法。您不应该在模型视图映射中使用任何类型的“反射”。
  • 那么当您在项目列表上使用 EditorFor 时,MVC 框架是如何做到的呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 2013-01-12
  • 1970-01-01
  • 2018-06-24
相关资源
最近更新 更多