asp.net-mvc – ASP.NET MVC(4) – 按特定顺序绑定属性
发布时间:2020-12-16 07:45:21 所属栏目:asp.Net 来源:网络整理
导读:有没有办法在C之前强制绑定属性A和B? System.ComponentModel.DataAnnotations.DisplayAttribute类中有Order属性,但它是否会影响绑定顺序? 我想要实现的是 page.Path = page.Parent.Path + "/" + page.Slug 在自定义的ModelBinder中 解决方法 我最初会推荐S
有没有办法在C之前强制绑定属性A和B?
System.ComponentModel.DataAnnotations.DisplayAttribute类中有Order属性,但它是否会影响绑定顺序? 我想要实现的是 page.Path = page.Parent.Path + "/" + page.Slug 在自定义的ModelBinder中 解决方法
我最初会推荐Sams回答,因为它根本不涉及Path属性的任何绑定.您提到可以使用Path属性连接值,因为这会导致延迟加载.因此,我想您正在使用域模型向视图显示信息.因此,我建议使用视图模型仅显示视图中所需的信息(然后使用Sams回答来检索路径),然后使用工具将视图模型映射到域模型(即
AutoMapper).
但是,如果继续在视图中使用现有模型,并且无法使用模型中的其他值,则可以在发生其他绑定后将path属性设置为自定义模型绑定器中表单值提供程序提供的值. (假设不对路径属性执行验证). 所以我们假设你有以下观点: @using (Html.BeginForm()) { <p>Parent Path: @Html.EditorFor(m => m.ParentPath)</p> <p>Slug: @Html.EditorFor(m => m.Slug)</p> <input type="submit" value="submit" /> } 以下视图模型(或视情况而定的域模型): 公共类IndexViewModel 然后,您可以指定以下模型绑定器: public class IndexViewModelBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext,ModelBindingContext bindingContext) { //Note: Model binding of the other values will have already occurred when this method is called. string parentPath = bindingContext.ValueProvider.GetValue("ParentPath").AttemptedValue; string slug = bindingContext.ValueProvider.GetValue("Slug").AttemptedValue; if (!string.IsNullOrEmpty(parentPath) && !string.IsNullOrEmpty(slug)) { IndexViewModel model = (IndexViewModel)bindingContext.Model; model.Path = bindingContext.ValueProvider.GetValue("ParentPath").AttemptedValue + "/" + bindingContext.ValueProvider.GetValue("Slug").AttemptedValue; } } } 最后,在视图模型上使用以下属性指定要使用此模型绑定器: [ModelBinder(typeof(IndexViewModelBinder))] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ASP.NET-MVC(IIS6)高流量时出错:指定的强制转换无效
- asp.net-mvc – 剃刀替换的优点(@href)
- 分享一个很早之前写的小工具DtSpyPlus
- asp.net – 会话状态,页面生命周期中的应用程序状态在哪里?
- Asp.net Core中SignalR Core预览版的一些新特性前瞻,附源码
- ASP.NET MVC 4和Entity Framework 5.0中的MySQL连接 – 多个
- asp.net-core – 在VS 2015 RC中,编译保存不适用于ASP.NET
- asp.net-mvc – 如何在ASP.NET MVC应用程序中实现搜索功能
- asp.net – 找不到元素’elmah’的架构信息
- iis-7 – localhost上的IIS非常慢
推荐文章
站长推荐
- asp.net-mvc – 获取文件夹中的文件
- asp.net-mvc – 使用Html.ActionLink传递文本框值
- asp.net-mvc – AttributeRouting ActionLink帮助
- 如果没有Visual Studio 2015,我们如何创建.NET
- asp.net-mvc – 具有SelectList(s)最佳实践的ASP
- asp.net – SignalR在.NET客户端和服务器之间的安
- 基于 Roslyn 实现一个简单的条件解析引擎
- asp.net-mvc – Visual Studio 2017增加了缺失的
- asp.net-web-api – 如何在每次请求后延长令牌过
- asp.net – 没有透明度的div中的div的不透明度
热点阅读