asp.net-mvc – MVC ViewModel绑定构造与展平
在我的ViewModel中(也在我的域模型中),我有一个动态的属性结构,其中Profile元素是基类ProfileVM的List并引用ProfileDefinitionElement(只是为了解释ViewModel而不粘贴整个东西).
public class OwnProfileVM { public OwnProfileVM() {} public ProfileDefinitionVM ProfileDefinitionVM { get; set; } public ProfileVM ProfileVM { get; set; } } 所以我使用Linq Single语句绑定我的属性: @Model.ProfileDefinitionVM.ProfileElementDefinitions.Single(p => p.Key == ProfileElementKey.CompanyName.ToString()).Title 这适用于显示数据.但是当这样回帖时: @Html.TextBoxFor(model => ((ProfileElementTextVM)model.ProfileVM.ProfileElements .Single(p=> p.ProfileElementDefinition.Key == ProfileElementKey.CompanyName.ToString())) .Text ..模型属性为null. 经过一些研究,我发现有两种方法可以解决这个问题: >“展平”ViewModel.所以我会为每个Profile Element提供一个固定的属性.这可行,但缺点是我无法使用Automapper映射数据.我必须“手动”将ViewModel填充到模型中.这将导致Controller中的代码更多,并且“更大”,但更简单的ViewModel.见于this article 现在我的问题: >第二种方式是否可行,如果是,将如何做?我还没有办法做到这一点. 解决方法
看起来很复杂最好简化一下.
根据我的经验,控制器中的模型属性为null,因为绑定器无法理解如何将表单元素名称与关联的属性相关联.例如,我已经看到了使用foreach的列表: (model has a) List<Something> Somethings..... foreach (Something thing in Model.Somethings) { @Html.EditorFor(m => thing) } 这在生成的html中呈现为< input name =“thing”.....这是无用的.这里的解决方案是使用for循环并通过其路径访问模型的属性,而不是复制指向实例的指针,例如: for (int i = 0; i < Model.Somethings.Count; i++) { @Html.EditorFor(m => Model.Somethings[i]) } 然后用正确的< input name =“Model.Somethings [i]”.....渲染,并且模型绑定器将理解它. 我希望你在这里遇到的这个问题是类似的.您需要向属性添加必要的访问器,以便在视图中呈现正确的名称和ID,并由绑定器选取. 我不确定你班级的确切定义,所以这个例子不太可能完全正确. 这个类包含一个this [string index]方法,它将使用你的属性键作为索引来获取和设置元素: public class ProfileElements : List<ProfileElement> { public ProfileElement this[string index] { get { return base.First(p => p.ProfileElementDefinition.Key == index); } set { base[index] = value; } } } 在您看来,您可以使用以下内容: @Html.TextBoxFor(model => model.ProfileVM.ProfileElements[ProfileElementKey.CompanyName.ToString()].Text) 希望这能满足您的需求. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – 控制器!=业务层?
- 如何在asp.net MVC3 Razor上编写html字段
- asp.net – CSS中的内联样式与样式
- 支持Ajax跨域访问ASP.NET Web Api 2(Cors)的示例教程
- asp.net – 在服务器端运行VBA功能从WCF服务访问数据库
- ASP.net HttpRuntime.Cache使用的默认序列化是什么
- 错误的请求 – 无效的主机名ASP.NET MVC4
- 3.翻译系列:EF Code-First 示例(EF 6 Code-First系列)
- asp.net-mvc – 当路由有多个值时如何构建RouteValueDictio
- asp-classic – Request.BinaryRead(Request.TotalBytes)抛
- asp.net – 缓存viewstate?
- asp.net – Azure应用程序中的4分钟超时
- asp.net-mvc – 使用默认控制器的ASP.NET MVC路由
- 在Entity Framework中使用存储过程(三):逻辑删
- asp.net-mvc – EF 4.1 Code First:“非空值类型
- .net – 一键更新所有WCF服务参考(两次点击也可以
- ASP.Net:尝试处理http:// localhost:5957 / h
- asp.net – 在web.config中设置信任级别
- asp.net – 在HTTP POST IIS ASP .NET上出现HTTP
- [ASP.NET MVC] 产生一维条码Barcode(Code 39、Co