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个元素中的每个元素呈现相应的编辑器模板.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....