asp.net core 自定义模型绑定器仅适用于一个属性 [英] asp.net core custom model binder just for one property
问题描述
我的 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;
}
}
我的模型(请注意,只有一个属性有我的自定义模型绑定器注释):
My model (and notice, only one property has my custom model binder annotation):
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 core 自定义模型绑定器仅适用于一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!