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页面编写它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – 服务器随机返回状态码为200的空响应
- asp.net-mvc – 构建视图模型的最佳方法是什么?
- ASP.NET OpenWebConfiguration失败
- asp.net-web-api – 在WebAPI中的TaskScheduler.Unobserved
- asp.net-web-api – 间歇性“无法加载类型”System.Net.Htt
- ASP.NET Server.Transfer()问题
- ASP / C#会话变量 – 未将对象引用设置为对象的实例
- asp.net – 如何在运行时设置ObjectDataSource选择参数
- ASP.NET网站与ASP.NET WebApp:性能差异是什么?
- asp.net-mvc-4 – 具有动态部分视图创建的MVC Ajax
推荐文章
站长推荐
- asp.net – 从RouteBase.GetVirtualPath返回绝对
- ASP.NET MVC学习之NuGet在VS中的运用浅谈
- asp.net – SQL Server 2005 – 您应该多久重建一
- asp.net-mvc – 从一个项目到另一个项目调用控制
- asp.net – 在web.config和asp页面中注册用户控件
- 为什么我的asp.net应用程序抛出ThreadAbortExcep
- asp.net-mvc – 将Orchard CMS部署到共享主机的正
- asp.net – 在启用了共享配置的IIS 7上安装Web D
- asp.net – 如何在不构建网站的情况下使用MSBuil
- 双重登录ASP.Net WebForms应用程序的一些用户
热点阅读