c# - ModelState 在表单提交时无效 - 需要 IEnumerable<SelectListItem>

标签 c# asp.net-mvc asp.net-core

我有一个添加分支机构的表单,该表单有一个下拉菜单用于选择公司名称。 我创建了一个 viewModel,其中包含公司的 SelectListItem 和分支模型 提交表单时,modelState.IsValid 等于 false。 原因是因为需要 CompaniesList。 知道为什么需要它吗?我该如何克服这个问题?

分支模型:

public class Branch
    {
        public int Id { get; set; }
        public int CompanyId { get; set; }
        [MaxLength(50)]
        public string? City { get; set; }
        [MaxLength(50)]
        public string? BranchName { get; set; }
        public DateTime CreatedAt { get; set; }
        [MaxLength(100)]
        public string? CreatedBy { get; set; }
    }

View 模型:

public class BranchVM
{
    public Branch branch { get; set; }
    [AllowNull]
    public IEnumerable<SelectListItem> CompaniesList { get; set; }
}

创建.cshtml:

@model Click2Lock.Models.BranchVM

<form method="post"  enctype="multipart/form-data">
    <div class="border p-3 mt-4">
        <div class="row pb-2">
            <h2 class="text-primary">Create Branch</h2>
            <hr/>
        </div>
        <div class="col-8">
            <label asp-for="branch.BranchName">Branch Name</label>
            <input asp-for="branch.BranchName" class="form-control"/>
            <span asp-validation-for="branch.BranchName" class="text-danger"></span>
        </div>
        <div class="col-8">
            <label asp-for="branch.City">City</label>
            <input asp-for="branch.City" class="form-control"/>
            <span asp-validation-for="branch.City" class="text-danger"></span>
        </div>
        <div class="col-8 pb-4">
           <div class="form-group row">
                    <div class="col-4">
                        <label asp-for="branch.CompanyId">Company</label>
                    </div>
                    <div class="col-8">
                        @Html.DropDownListFor(m => m.branch.CompanyId, Model.CompaniesList , "Select Order",
                       new { @class = "form-control" })
                        <span asp-validation-for="branch.CompanyId" class="text-danger"></span>
                    </div>
                </div>
     </div>
         <div class="col-8">
                <input type="hidden" asp-for="branch.CreatedAt" class="form-control" value="@DateTime.Now" />
            </div>
            <div class="col-8">
                <input type="hidden" asp-for="branch.CreatedBy" class="form-control" <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4036212c35257d00162925370221276e353325320e212d25" rel="noreferrer noopener nofollow">[email protected]</a> />
            </div>
        <button type="submit" class="btn btn-primary" style="width:200px">Add New Branch</button>
        <a asp-controller="Company" asp-action="Index" class="btn btn-secondary" style="width:150px">
            Back To List
        </a>

    </div>
</form>

在 Controller 上创建:

public IActionResult Create()
{
    ViewBag.userName = (_unitOfWork.ApplicationUser.GetAll().
       Where(q => q.UserName == User.Identity.Name).Select(q => q.FullName)).FirstOrDefault();

    BranchVM branchVM = new BranchVM()
    {
        branch = new Branch(),
        CompaniesList = _unitOfWork.Company.GetAll().OrderBy(a=>a.CompanyName).
        Select(i => new SelectListItem
        {
            Text = i.CompanyName,
            Value = i.Id.ToString()
        })
    };
    return View(branchVM);
}
//POST
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(BranchVM branchVM)
{
    ViewBag.msgCreate = 0;
    ViewBag.msgGeneralException = 0;

    if (ModelState.IsValid)
    {
        try
        {
            _unitOfWork.Branch.Add(branchVM.branch);
            _unitOfWork.Save();
            ViewBag.msgCreate = 1;
            return View(branchVM);
        }
        catch (Exception ex)
        {
            ViewBag.msgGeneralException = 1;
            return View(branchVM);
        }
        
    }
    ViewBag.msgGeneralException = 1;
    return View(branchVM);
}

最佳答案

一种技术是使其可为空:

public IEnumerable<SelectListItem>? CompaniesList { get; set; }

关于c# - ModelState 在表单提交时无效 - 需要 IEnumerable<SelectListItem>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71001414/

相关文章:

c# - WinRt C#音频库

asp.net - 在 ASP.NET MVC 中将集合传递给 EditorFor

asp.net-mvc - OAuth.dll 使用比 webMatrix.data 和 webmatrix.webdata 引用的程序集更高的版本

c# - 使用 Azure AD 时处理 Asp.Net MVC 中的 token 超时

c# - Entity Framework Core 3.0 - Include 中使用的 Lambda 表达式无效

c# - 匿名类型列表?

C# 泛型类型转换 Decimal 到 Float - "Cannot convert type ' T1 ?' to ' T 2'"

c# - 使用 C# 中的 2D 字符串数组填充 JavaScript 数组

c# - 如何在 Server.MapPath 的 ASP.Net Core 替代方法中获取绝对路径

asp.net-core - 如何检测我的应用程序是否在 AWS 中运行