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

前端之家收集整理的这篇文章主要介绍了asp.net-core – asp.net核心自定义模型绑定器,仅适用于一个属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的asp.net核心控制器有一个简单的模型:
  1. [HttpPost]
  2. public async Task<DefaultResponse> AddCourse([FromBody]CourseDto dto)
  3. {
  4. var response = await _courseService.AddCourse(dto);
  5. return response;
  6. }

我的模型是:

  1. public class CourseDto
  2. {
  3. public int Id { get; set; }
  4. public string Name { get; set; }
  5. public string Genre { get; set; }
  6. public string Duration { get; set; }
  7. public string Level { get; set; }
  8. public string AgeRange { get; set; }
  9. public string Notes { get; set; }
  10. public bool Active { get; set; }
  11. public string OrganisationCode { get; set; }
  12. }

我正在尝试使用自定义模式绑定器或动作过滤器设置“OrganisationCode”的值,但没有成功.
如果你在执行动作之前建议更新模型的正确方法,我会很蠢.

谢谢.

解决方法

我将在这里向您展示一个非常简单的自定义模型绑定器,我刚刚编写(并在.Net Core 2.0中测试过):

我的模型粘合剂:

  1. public class CustomModelBinder : IModelBinder
  2. {
  3. public Task BindModelAsync(ModelBindingContext bindingContext)
  4. {
  5. var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  6. var value = valueProviderResult.FirstValue; // get the value as string
  7.  
  8. var model = value.Split(",");
  9. bindingContext.Result = ModelBindingResult.Success(model);
  10.  
  11. return Task.CompletedTask;
  12. }
  13. }

我的模型(注意,只有一个属性自定义模型绑定器注释):

  1. public class CreatePostviewmodel
  2. {
  3. [Display(Name = nameof(ContentText))]
  4. [MinLength(10,ErrorMessage = ValidationErrors.MinLength)]
  5. public string ContentText { get; set; }
  6.  
  7. [BindProperty(BinderType = typeof(CustomModelBinder))]
  8. public IEnumerable<string> Categories { get; set; } // <<<<<< THIS IS WHAT YOU ARE INTERESTER IN
  9.  
  10. #region View Data
  11. public string PageTitle { get; set; }
  12. public string TitlePlaceHolder { get; set; }
  13. #endregion
  14. }

它的作用是:它接收一些文本,如“aaa,bbb,ccc”,并将其转换为数组,并将其返回给viewmodel.

我希望有所帮助.

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

猜你在找的asp.Net相关文章