【发布时间】:2019-10-14 10:16:58
【问题描述】:
这是我的模特
public class MyModel
{
public string Title { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public Guid InstructorId { get; set; }
}
这就是我计划将它与模型绑定器一起使用的方式。
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var model = new CreateCourseRequestModel();
var properties = typeof(CreateCourseRequestModel).GetProperties();
foreach (var property in properties)
{
var value = bindingContext.ValueProvider.GetValue(property.Name); // prop value
property.SetValue(model, value.FirstValue);
}
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
如果所有属性的类型都是string,那么没有问题。
如果任何属性不是字符串类型,那么应该有问题。
问题
如何将string 解析为模型绑定器中所需的属性类型?
谢谢
【问题讨论】:
-
你想在控制器动作中自动绑定模型吗?
-
CreateCourseRequestModel的定义是什么?您将自定义模型绑定器放在哪里?
标签: asp.net-core model-view-controller