【发布时间】: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