简体   繁体   English

ASP.NET MVC - ModelState 无效但可以访问表单内容

[英]ASP.NET MVC - ModelState is invalid but form content is acessible

I am trying to pass some input from the "Create" view to my controller but the ModelState is returning error:我正在尝试将“创建”视图中的一些输入传递给我的控制器,但 ModelState 返回错误:

The Controller:控制器:

[Route("Create")]
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create([Bind("Name, Location, MaxCapacity")] Warehouse warehouse)
{

    if (ModelState.IsValid)
    {
        _Db.Add(warehouse);
        _Db.SaveChanges();
        return RedirectToAction("Index");
    }

    return BadRequest();
}

The view:风景:

@model InventoryManSys.Models.Warehouse

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Warehouse</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Location" class="control-label"></label>
                <input asp-for="Location" class="form-control" />
                <span asp-validation-for="Location" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="MaxCapacity" class="control-label"></label>
                <input asp-for="MaxCapacity" class="form-control" />
                <span asp-validation-for="MaxCapacity" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

The model:该模型:

public class Warehouse
{
    [Key]
    public int Id { get; set; }
    [Required]
    [StringLength(30, ErrorMessage = "Name should have less than 30 characters")]
    [DisplayName("Warehouse Name")]
    public string Name { get; set; }
    [Required]
    public string Location { get; set; }
    [Required]
    public int MaxCapacity { get; set; }

    //Navigation Property
    public ICollection<Category> Categories { get; set; }

}

But when I do a "Console.WriteLine(warehouse.Name)" the input is being passed correctly.但是当我执行“Console.WriteLine(warehouse.Name)”时,输入被正确传递。 How to solve that?如何解决? is the "bind[]"attribute a problem? “bind[]”属性有问题吗?

ModelState is invalid but form content is acessible ModelState 无效,但可以访问表单内容

You may add the client validation js library jquery.validate.js and jquery.validate.unobtrusive.js .您可以添加客户端验证 js 库jquery.validate.jsjquery.validate.unobtrusive.js

Check this document:检查这个文件:

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0#client-side-validation https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0#client-side-validation

If Name / Location / MaxCapacity are received value, it should work fine, suggest you can check the ModelState or just return BadRequest(ModelState);如果接收到Name / Location / MaxCapacity值,它应该可以正常工作,建议您可以检查ModelState或只return BadRequest(ModelState); to see what's the detailed error.看看详细的错误是什么。

But if you use .NET 6 , as this document said:但是,如果您使用 .NET 6 ,如本文档所述:

Beginning with .NET 6, new projects include the <Nullable>enable</Nullable> element in the project file.从 .NET 6 开始,新项目在项目文件中包含<Nullable>enable</Nullable>元素。 Once the feature is turned on, existing reference variable declarations become non-nullable reference types .开启该功能后,现有的引用变量声明将变为不可为空的引用类型

So that the non-nullable property must be required in ASP.NET 6, otherwise the ModelState will be invalid.因此在 ASP.NET 6 中必须要求不可为空的属性,否则 ModelState 将无效。

One way is to remove <Nullable>enable</Nullable> from your project file.一种方法是从项目文件中删除<Nullable>enable</Nullable>

Another way is to add ?另一种方法是添加? like below:如下所示:

public class Warehouse
{
    [Key]
    public int? Id { get; set; }
    [Required]
    [StringLength(30, ErrorMessage = "Name should have less than 30 characters")]
    [DisplayName("Warehouse Name")]
    public string Name { get; set; }
    [Required]
    public string Location { get; set; }
    [Required]
    public int MaxCapacity { get; set; }

    //Navigation Property
    public ICollection<Category>? Categories { get; set; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM