加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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 string ParentPath {get;组; }
????public string Slug {get;组; }
????public string Path {get;组; }
}

然后,您可以指定以下模型绑定器:

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))]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读