【问题标题】:How to convert string to value type on model binding in ASP.NET Core mvc如何在 ASP.NET Core mvc 中的模型绑定上将字符串转换为值类型
【发布时间】: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


【解决方案1】:

我有一个问题。为什么要使用自定义模型绑定器?

默认可以毫无问题地处理您当前的示例模型。

[HttpPost]
public Task<IActionResult> Post(MyModel model) { .. }

在控制器中应该可以工作。

或者也许我误解了你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多