如何处理复杂类型的模型绑定与接口列表和嵌套的接口列表,可能没有值

问题描述 投票:0回答:1

我已经成功(可能没有优雅地)创建了一个模型绑定器,它将在post上绑定一个接口列表。每个接口都有单独的属性,有些具有另一个接口的嵌套List。接口列表在视图中正确显示,嵌套列表项也是如此。在帖子上一切正常,调用自定义模型绑定器并构建正确的类型。我遇到的问题是,如果嵌套的接口列表没有要显示的项目,则在回发后,模型绑定器将不会构建该对象以及之后的任何对象。

我正在使用剃刀页面及其各自的页面模型。我在pagemodel中使用了[BindProperty]注释。

接口和对象

使用具体实现修剪接口:我已经删除了类并省略了不必要的代码...

public interface IQuestion
{
    Guid Number{ get; set; }
    string Text{ get; set; }
    List<IAnswer> AnswerList{ get; set; }
    ..
}
public interface IAnswer
    {
        string Label { get; set; }
        string Tag { get; set; }
        ..
    }
public class MetaQuestion: IQuestion
    {
        public int Number{ get; set; }
        public string Text{ get; set; }
        public List<IAnswer> AnswerList{ get; set; }
        ..
    }
public class Answer: IAnswer
    {
        public string Label { get; set; }
        public string Tag { get; set; }
        ..
    }

剃刀页面模型

public class TestListModel : PageModel
    {
        private readonly IDbSession _dbSession;

        [BindProperty]
        public List<IQuestion> Questions { get; set; }

        public TestListModel(IDbSession dbSession)
        {
            _dbSession= dbSession;
        }

        public async Task OnGetAsync()
        {
            //just to demonstrate where the data is comming from
            var allQuestions = await _dbSession.GetAsync<Questions>();

            if (allQuestions == null)
            {
                return NotFound($"Unable to load questions.");
            }
            else
            {                
                Questions = allQuestions;
            }
        }

        public async Task<IActionResult> OnPostAsync()
        {
            //do something random with the data from the post back
            var question = Questions.FirstOrDefault();
            ..          
            return Page();
        }
    }

生成的Html

这是生成的代码的html不起作用。其中一个问题项目,特别是列表中的第二个项目,在Answers中没有任何AnswerList

我们可以看到,列表中的第二个问题在AnswerList中没有'Answer'项。这意味着在回发后,我只收到列表中的第一个问题。如果我从列表中删除第二个问题,那么我会回答所有问题。

为了简洁起见,我删除了所有样式,类和div。

问题1:

<input id="Questions_0__Number" name="Questions[0].Number" type="text" value="sq1">
<input id="Questions_0__Text" name="Questions[0].Text" type="text" value="Are you:">
<input name="Questions[0].TargetTypeName" type="hidden" value="Core.Model.MetaData.MetaQuestion, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<input data-val="true" data-val-required="The Tag field is required." id="Questions_0__AnswerList_0__Tag" name="Questions[0].AnswerList[0].Tag" type="text" value="1">
<input id="Questions_0__AnswerList_0__Label" name="Questions[0].AnswerList[0].Label" type="text" value="Male">
<input id="Questions_0__AnswerList_0__TargetTypeName" name="Questions[0].AnswerList[0].TargetTypeName" type="hidden" value="Core.Common.Implementations.Answer, Core.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">

问题2:

<input id="Questions_1__Number" name="Questions[1].Number" type="text" value="sq1">
<input id="Questions_1__Text" name="Questions[1].Text" type="text" value="Are you:">
<input name="Questions[1].TargetTypeName" type="hidden" value="Core.Model.MetaData.MetaQuestion, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">

问题2之后的其余问题与问题1类似。

自定义模型绑定器和提供程序

我知道这不是最好的方法,包括TargetTypeName并不理想。真的没有太多可以找到帮助解决这个问题。对于ASP web dev,我是新手。

public class IQuestionModelBinder : IModelBinder
    {
        private readonly IDictionary<Type, ComplexTypeModelBinder> modelBuilderByType;

        private readonly IModelMetadataProvider modelMetadataProvider;

        public IQuestionModelBinder(IDictionary<Type, ComplexTypeModelBinder> modelBuilderByType, IModelMetadataProvider modelMetadataProvider)
        {
            this.modelBuilderByType = modelBuilderByType ?? throw new ArgumentNullException(nameof(modelBuilderByType));
            this.modelMetadataProvider = modelMetadataProvider ?? throw new ArgumentNullException(nameof(modelMetadataProvider));
        }

        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var str = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "TargetTypeName");

            var modelTypeValue = bindingContext.ValueProvider.GetValue(ModelNames.CreatePropertyModelName(bindingContext.ModelName, "TargetTypeName"));

            if (modelTypeValue != null && modelTypeValue.FirstValue != null)
            {
                Type modelType = Type.GetType(modelTypeValue.FirstValue);
                if (this.modelBuilderByType.TryGetValue(modelType, out var modelBinder))
                {
                    ModelBindingContext innerModelBindingContext = DefaultModelBindingContext.CreateBindingContext(
                        bindingContext.ActionContext,
                        bindingContext.ValueProvider,
                        this.modelMetadataProvider.GetMetadataForType(modelType),
                        null,
                        bindingContext.ModelName);

                    modelBinder.BindModelAsync(innerModelBindingContext);

                    bindingContext.Result = innerModelBindingContext.Result;
                    return Task.CompletedTask;
                }
            }

            bindingContext.Result = ModelBindingResult.Failed();
            return Task.CompletedTask;
        }
    }

提供者:

 public class IQuestionModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Metadata.ModelType == typeof(IQuestion))
            {
                var assembly = typeof(IQuestion).Assembly;
                var metaquestionClasses = assembly.GetExportedTypes()
                    .Where(t => !t.IsInterface || !t.IsAbstract)
                    .Where(t => t.BaseType.Equals(typeof(IQuestion)))
                    .ToList();

                var modelBuilderByType = new Dictionary<Type, ComplexTypeModelBinder>();

                foreach (var type in metaquestionClasses)
                {
                    var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
                    var metadata = context.MetadataProvider.GetMetadataForType(type);

                    foreach (var property in metadata.Properties)
                    {
                        propertyBinders.Add(property, context.CreateBinder(property));
                    }

                    modelBuilderByType.Add(type, new ComplexTypeModelBinder(propertyBinders: propertyBinders));
                }

                return new IMetaQuestionModelBinder(modelBuilderByType, context.MetadataProvider);
            }

            return null;
        }

类似于IAnswer接口(可能重构为没有2个绑定器):

  public class IAnswerModelBinder : IModelBinder
    {
        private readonly IDictionary<Type, ComplexTypeModelBinder> modelBuilderByType;

        private readonly IModelMetadataProvider modelMetadataProvider;

        public IAnswerModelBinder(IDictionary<Type, ComplexTypeModelBinder> modelBuilderByType, IModelMetadataProvider modelMetadataProvider)
        {
            this.modelBuilderByType = modelBuilderByType ?? throw new ArgumentNullException(nameof(modelBuilderByType));
            this.modelMetadataProvider = modelMetadataProvider ?? throw new ArgumentNullException(nameof(modelMetadataProvider));
        }

        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var str = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "TargetTypeName");

            var modelTypeValue = bindingContext.ValueProvider.GetValue(ModelNames.CreatePropertyModelName(bindingContext.ModelName, "TargetTypeName"));

            if (modelTypeValue != null && modelTypeValue.FirstValue != null)
            {
                Type modelType = Type.GetType(modelTypeValue.FirstValue);
                if (this.modelBuilderByType.TryGetValue(modelType, out var modelBinder))
                {
                    ModelBindingContext innerModelBindingContext = DefaultModelBindingContext.CreateBindingContext(
                        bindingContext.ActionContext,
                        bindingContext.ValueProvider,
                        this.modelMetadataProvider.GetMetadataForType(modelType),
                        null,
                        bindingContext.ModelName);

                    modelBinder.BindModelAsync(innerModelBindingContext);

                    bindingContext.Result = innerModelBindingContext.Result;
                    return Task.CompletedTask;
                }
            }

            bindingContext.Result = ModelBindingResult.Failed();
            return Task.CompletedTask;
        }
    }

提供者:

 public class IAnswerModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Metadata.ModelType == typeof(IAnswer))
            {
                var exportedTypes = typeof(IAnswer).Assembly.GetExportedTypes();

                var metaquestionClasses = exportedTypes
                    .Where(y => y.BaseType != null && typeof(IAnswer).IsAssignableFrom(y) && !y.IsInterface)
                    .ToList();

                var modelBuilderByType = new Dictionary<Type, ComplexTypeModelBinder>();

                foreach (var type in metaquestionClasses)
                {
                    var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();
                    var metadata = context.MetadataProvider.GetMetadataForType(type);

                    foreach (var property in metadata.Properties)
                    {
                        propertyBinders.Add(property, context.CreateBinder(property));
                    }

                    modelBuilderByType.Add(type, new ComplexTypeModelBinder(propertyBinders: propertyBinders));
                }

                return new IAnswerModelBinder(modelBuilderByType, context.MetadataProvider);
            }

            return null;
        }

这些都注册如下:

  services.AddMvc(
                options =>
                {
                    // add custom binder to beginning of collection (serves IMetaquestion binding)
                    options.ModelBinderProviders.Insert(0, new IMetaQuestionModelBinderProvider());
                    options.ModelBinderProviders.Insert(0, new IAnswerModelBinderProvider());
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2));

我试图提供尽可能多的信息。

我已经在这几天了,最终除了这一个案例之外,还有所有绑定工作。

有助于实现这一目标的SO帖子:

我知道模型绑定器使用递归,这使我相信发生了一些事情,一旦它击中没有Question值的AnswerList就停止执行。

我唯一注意到的是html中的AnswerList Tag属性将data-val设置为true,data-val-required也是如此。

<input data-val="true" data-val-required="The Tag field is required." id="Questions_0__AnswerList_0__Tag" name="Questions[0].AnswerList[0].Tag" type="text" value="1"

我不知道为什么会这样。我没有明确地说明这一点。该类位于不同的命名空间中,我们宁愿不在整个类中应用数据注释。

这可能是什么打破了绑定,因为它期待一个值,但我不能确定。

这个问题是正常行为吗?如果是这样,解决方案是什么?

c# model-binding razor-pages asp.net-core-2.2
1个回答
0
投票

我将继续回答我自己的问题。这解决了这个问题。这是我的编辑器模板看起来像Question

@model MetaQuestion
<div class="card card form-group" style="margin-top:10px;">
    <div class="card-header">
        <strong>
            @Html.TextBoxFor(x => x.Number, new { @class = "form-control bg-light", @readonly = "readonly", @style = "border:0px;" })
        </strong>
    </div>
    <div class="card-body text-black-50">
        <h6 class="card-title mb-2 text-muted">
            @Html.TextBoxFor(x => x.Text, new { @class = "form-control", @readonly = "readonly", @style = "background-color:white; border:0px;" })
        </h6>
        @for (int i = 0; i < Model.AnswerList.Count; i++)
        {
        <div class="row">
            <div class="col-1">
                @Html.TextBoxFor(x => x.AnswerList[i].PreCode, new { @class = "form-control", @readonly = "readonly", @style = "background-color:white; border:0px;" })
            </div>
            <div class="col">
                @Html.TextBoxFor(x => x.AnswerList[i].Label, new { @class = "form-control", @readonly = "readonly", @style = "background-color:white; border:0px;" })
            </div>
            <div class="col-1">
                @Html.HiddenFor(x => x.AnswerList[i].TargetTypeName)
            </div>
            <div class="col-1">
                <input name="@(ViewData.TemplateInfo.HtmlFieldPrefix + ".TargetTypeName")" type="hidden" value="@this.Model.GetType().AssemblyQualifiedName" />
            </div>
        </div>
        }
    </div>
</div>

接近尾声你可以看到有2列包括HiddenFor助手。我正在使用这些来识别接口的类型,它允许我的问题中提到的自定义模型绑定器选择相关类型。

对我来说不明显的是,当'问题'没有'答案'时,它忽略了for循环内外的所有值。因此,自定义绑定器永远无法找到Question的类型,因为数据完全丢失了。

我已经开始重新订购解决了这个问题的Html.HiddenFor助手。我的编辑器现在看起来如下:

@model MetaQuestion
<div class="card card form-group" style="margin-top:10px;">
    <div class="card-header">
        <input name="@(ViewData.TemplateInfo.HtmlFieldPrefix + ".TargetTypeName")" type="hidden" value="@this.Model.GetType().AssemblyQualifiedName" />
        <strong>
            @Html.TextBoxFor(x => x.Number, new { @class = "form-control bg-light", @readonly = "readonly", @style = "border:0px;" })
        </strong>
    </div>
    <div class="card-body text-black-50">
        <h6 class="card-title mb-2 text-muted">
            @Html.TextBoxFor(x => x.Text, new { @class = "form-control", @readonly = "readonly", @style = "background-color:white; border:0px;" })
        </h6>
        @for (int i = 0; i < Model.AnswerList.Count; i++)
        {
            @Html.HiddenFor(x => x.AnswerList[i].TargetTypeName)
            <div class="row">
                <div class="col-1">
                    @Html.TextBoxFor(x => x.AnswerList[i].PreCode, new { @class = "form-control", @readonly = "readonly", @style = "background-color:white; border:0px;" })
                </div>
                <div class="col">
                    @Html.TextBoxFor(x => x.AnswerList[i].Label, new { @class = "form-control", @readonly = "readonly", @style = "background-color:white; border:0px;" })
                </div>
            </div>
        }
    </div>
</div>

预先放置它确保它始终存在。这可能不是处理整个情况的最佳方式,但至少它解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.