【问题标题】:Model is null in when Post data to controller Asp.Net Core MVC将数据发布到控制器 Asp.Net Core MVC 时模型为空
【发布时间】:2020-09-23 15:19:44
【问题描述】:

我有一个带有文本区域的表单,当我输入的字符数少于 200 时,工作正常。如果字符数限制超过 200,则在我提交表单时,我的整个模型将变为空。

所以我现在添加了最大长度属性,但我的要求是输入最大字符。我的代码sn-p如下

模型为

[BindProperty]
 [Required(ErrorMessage ="notes are required")]
 [MaxLength(200)]
 public string Notes { get; set; }

我的控制器如下

[HttpPost]
[Route("notes")]
public async Task<JsonResult> AddNotes(ProfileReviewNotesViewModel model)
{
   var response = await this.profileModelBuilder.SaveNots(model, UserId);
   return Json(response);
}

请帮我解决这个问题。

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    您需要使用ModelState.IsValid。基本上如果模型有错误,属性不会被填充,而是 ModelState.IsValid = false 和 ModelState 包含错误。

    [HttpPost]
    [Route("notes")]
    public async Task<JsonResult> AddNotes(ProfileReviewNotesViewModel model)
    {
       if ( !ModelState.IsValid )
           return <bad request> //here
    
    
       var response = await this.profileModelBuilder.SaveNots(model, UserId);
       return Json(response);
    }
    

    【讨论】:

    • 非常感谢。我收到错误,因为无法读取请求表。超出表单值长度限制 200。有什么办法可以增加表单的值长度?
    • 未能读取申请表。表单值长度限制超过 200
    • 我终于解决了这个问题。我们需要使用 enctype="multipart/form-data".. 非常感谢您帮助我找出根本原因
    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多