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

asp.net-core – asp.net核心自定义模型绑定器,仅适用于一个属性

发布时间:2020-12-15 22:25:55 所属栏目:asp.Net 来源:网络整理
导读:我的asp.net核心控制器有一个简单的模型: [HttpPost]public async TaskDefaultResponse AddCourse([FromBody]CourseDto dto){ var response = await _courseService.AddCourse(dto); return response;} 我的模型是: public class CourseDto{ public int Id
我的asp.net核心控制器有一个简单的模型:
[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”的值,但没有成功.
如果你在执行动作之前建议更新模型的正确方法,我会很蠢.

谢谢.

解决方法

我将在这里向您展示一个非常简单的自定义模型绑定器,我刚刚编写(并在.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.

我希望有所帮助.

免责声明:我不是模型粘合剂写作的专家,15分钟前我已经知道了,我找到了你的问题(没有有用的答案),所以我试着帮忙.这是一个非常基本的模型粘合剂,肯定需要一些改进.我学会了如何从official documentation页面编写它.

(编辑:李大同)

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

    推荐文章
      热点阅读