我的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页面编写它.