【问题标题】:How to bind an Interface to a Razor form如何将接口绑定到 Razor 表单
【发布时间】:2020-02-09 19:07:00
【问题描述】:

我有一个 Razor 表单(来自脚手架),绑定到一个接口:

public class CreateModel : PageModel
{
    private readonly ImageStorm.DB.Core.ImagestormContext _context;

    public CreateModel(ImageStorm.DB.Core.ImagestormContext context)
    {
        _context = context;
    }

    public IActionResult OnGet()
    {
        return Page();
    }

    [BindProperty]
    public IImaging Imaging { get; set; } = new Imaging();

    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see https://aka.ms/RazorPagesCRUD.
    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Imagings.Add((Imaging)Imaging);
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

我为 EF.Core 类创建了一个接口,因此我可以将属性放在那里,而不必担心在更新模型时会丢失它们。

    public interface IImaging
    {
        string Cron { get; set; }
        [DataType(DataType.DateTime)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MMM-dd HH: mm}")]
        DateTime? CronEnd { get; set; }
        [DataType(DataType.DateTime)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MMM-dd HH: mm}")]
...

这对支架索引页面非常有用。

但是,当我将这种方法用于创建页面时,我在保存时收到以下错误:

InvalidOperationException:无法创建“ImageStorm.DB.Core.IImaging”类型的实例。模型绑定的复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。或者,在“ImageStorm.Client.CreateModel”构造函数中将“Imaging”属性设置为非空值。

Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.BindModelCoreAsync(ModelBindingContext bindingContext, int propertyData)
Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, object value)
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageBinderFactory+<>c__DisplayClass2_0+<<CreatePropertyBinder>g__Bind|0>d.MoveNext()
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.BindArgumentsCoreAsync()
Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

是否有解决方法或更好的方法?

【问题讨论】:

  • 错误信息很清楚Model bound complex types must not be abstract or value types and must have a parameterless constructor. 。使用具体的实现。

标签: asp.net asp.net-core razor


【解决方案1】:

如何将接口绑定到 Razor 表单

你没有。

错误信息很清楚

模型绑定的复杂类型不能是抽象类型或值类型,并且必须有无参数构造函数。 `

强调我的

使用具体实现。

public class CreateModel : PageModel {
    private readonly ImageStorm.DB.Core.ImagestormContext _context;

    public CreateModel(ImageStorm.DB.Core.ImagestormContext context) {
        _context = context;
    }

    public IActionResult OnGet() {
        return Page();
    }

    [BindProperty]
    public Imaging Imaging { get; set; } = new Imaging();//<-- NOTE USE OF IMPLEMENTATION 

    public async Task<IActionResult> OnPostAsync() {
        if (!ModelState.IsValid) {
            return Page();
        }

        _context.Imagings.Add(Imaging);
        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

参考Model Binding in ASP.NET Core

【讨论】:

  • 如果在 EF.Core 类上设置各种属性并绑定它们,它就可以工作。但是,当我更新模型时,所有这些编辑都会丢失。有什么策略可以避免这种情况吗?
猜你喜欢
  • 2019-12-15
  • 2013-09-17
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 2011-04-29
  • 1970-01-01
相关资源
最近更新 更多