asp.net核心自定义模型活页夹仅用于一种属性 [英] asp.net core custom model binder just for one property

查看:73
本文介绍了asp.net核心自定义模型活页夹仅用于一种属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的asp.net核心控制器,我有一个简单的模型:

I have a simple model for my asp.net core controller:

[HttpPost]
public async Task<DefaultResponse> AddCourse([FromBody]CourseDto dto)
{
     var response = await _courseService.AddCourse(dto);
     return response;
}

我的模型是:

 public class CourseDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Genre { get; set; }
    public string Duration { get; set; }
    public string Level { get; set; }
    public string AgeRange { get; set; }
    public string Notes { get; set; }
    public bool Active { get; set; }
    public string OrganisationCode { get; set; }
}

我正在尝试使用自定义模式绑定器或操作过滤器设置"OrganisationCode"的值,但没有成功. 如果您在执行操作之前提出更新模型的正确方法,我将不胜感激.

I'm trying to set value of "OrganisationCode" using a custom mode binder or action filter, but had no success. I would be thnakful if you advise whats the right way to updat ethe model before executing the action.

谢谢.

推荐答案

在这里,我将向您展示我刚刚编写(并在.Net Core 2.0中进行测试)的非常简单的自定义模型活页夹:

I will show you here a very simple custom model binder I have just written (and tested in .Net Core 2.0):

我的模型资料夹:

public class CustomModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var value = valueProviderResult.FirstValue; // get the value as string

        var model = value.Split(",");
        bindingContext.Result = ModelBindingResult.Success(model);

        return Task.CompletedTask;
    }
}

我的模型(注意,只有一个属性具有我的自定义模型活页夹批注):

public class CreatePostViewModel
{
    [Display(Name = nameof(ContentText))]
    [MinLength(10, ErrorMessage = ValidationErrors.MinLength)]
    public string ContentText { get; set; }

    [BindProperty(BinderType = typeof(CustomModelBinder))]
    public IEnumerable<string> Categories { get; set; } // <<<<<< THIS IS WHAT YOU ARE INTERESTER IN

    #region View Data
    public string PageTitle { get; set; }
    public string TitlePlaceHolder { get; set; }
    #endregion
}

它的作用是:它接收到诸如"aaa,bbb,ccc"之类的文本,并将其转换为数组,然后将其返回到ViewModel.

What it does is: it receives some text like "aaa,bbb,ccc", and converts it into array, and return it to the ViewModel.

我希望能帮上忙.

免责声明:我不是模型活页夹写作方面的专家,我在15分钟前就了解到这一点,并且找到了您的问题(没有有用的答案),因此我尝试提供帮助.这是一个非常基本的模型活页夹,肯定需要一些改进.我从

DISCLAIMER: I am not an expert in model binders writing, I have learnt that 15 minutes ago, and I found your question (with no helpful answer), so I tried to help. This is a very basic model binder, some improvements are surely required. I learned how to write it from the official documentation page.

这篇关于asp.net核心自定义模型活页夹仅用于一种属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆