asp.net-mvc-3 – 使用Html.EditorFor为新记录创建空白

使用EditorFor模板是ASP.Net MVC 3的一个非常好的功能,但是有可能让EditorFor呈现一个未填充的模板以允许创建记录吗?

或者还有其他方法可以做到这一点吗?

我试图这样做的方式如下:

@Html.EditorFor(model => model)
    @Html.EditorFor(x => new List<Business.viewmodel.Affiliate.Contact>())
    @Html.EditorFor(new List<Business.viewmodel.Affiliate.Contact>())
    @Html.EditorFor(new Business.viewmodel.Affiliate.Contact())

一个显然有效,但随后的(显示我正在尝试做的)都会失败并出现以下错误

Templates can be used only with field access,property access,single-dimension array index,or single-parameter custom indexer expressions.

有问题的模型是:

IEnumerable<Business.viewmodel.Affiliate.Contact>

解决方法

控制器负责准备将传递给视图的视图模型.因此,如果您需要以5个空联系人行初始化视图模型,则只需在控制器中执行此操作:
public ActionResult Index()
{
    var model = new Myviewmodel
    {
        // Add 5 empty contacts
        Contacts = Enumerable.Range(1,5).Select(x => new Contact()).ToList()
    };
    return View(model);
}

并在您的视图中像往常一样使用EditorFor助手:

@model Myviewmodel
...
@Html.EditorFor(x => x.Contacts)

这将为我们添加到Contacts集合中的5个元素中的每个元素呈现相应的编辑器模板.

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...