ASP.NET 核心 MVC 验证失败

ASP.NET Core MVC validation failure

我是 ASP.NET 核心 MVC 应用程序的新手。我正在尝试创建一个网络应用程序,但我在验证我的模型时遇到了问题。我添加了模型代码、控制器代码和剃须刀页面。我的模型验证失败,因为 razor 页面没有启动 il 模型。通常我不需要 iller 模型。

你介意任何人都可以帮助我关于没有自定义验证的验证有没有简单的解决方案。我正在使用 .NET Core 6.0 和 Visual Studio 2022

这是我的模型class

using System;
using System.Collections.Generic;

namespace OdevProject.Models
{
    public partial class Ilceler
    {
        public Ilceler()
        {
            Adreslers = new HashSet<Adresler>();
            Bolumlers = new HashSet<Bolumler>();
            Doktorlars = new HashSet<Doktorlar>();
            Hastanelers = new HashSet<Hastaneler>();
            Randevulars = new HashSet<Randevular>();
        }

        public int IlceId { get; set; }
        public int IlId { get; set; }
        public string IlceAd { get; set; } = null!;

        public virtual Iller Il { get; set; } = null!;
        public virtual ICollection<Adresler> Adreslers { get; set; }
        public virtual ICollection<Bolumler> Bolumlers { get; set; }
        public virtual ICollection<Doktorlar> Doktorlars { get; set; }
        public virtual ICollection<Hastaneler> Hastanelers { get; set; }
        public virtual ICollection<Randevular> Randevulars { get; set; }
    }
}

这是控制器

public async Task<IActionResult> Create([Bind("IlceId,IlId,IlceAd")] Ilceler ilceler)
{
    //var Il = new Iller { IlId = ilceler.Il.IlId, IlAd=ilceler.Il.IlAd };
    if (ModelState.IsValid)
    {
        var ilce = _context.Ilcelers.Where(x => x.IlceAd == ilceler.IlceAd).FirstOrDefault();

        if (ilce != null)
        {
            ViewBag.Message = "Exist";
            return View();
        }
        else
        {
            _context.Add(ilceler);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }

    ViewData["IlId"] = new SelectList(await _context.Illers.ToListAsync(), "IlId", "IlAd");

    //ViewData["Illist"] = new SelectList(await _context.Illers.ToListAsync(), "IlId", "IlAd");
    //ViewData["IlId"] = new SelectList(_context.Illers, "IlId", "IlId", ilceler.IlId);
    return View(ilceler);
} 

最后是剃刀页面

@model OdevProject.Models.Ilceler 

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

<h1>Create</h1>

<h4>Ilceler</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="IlId" class="control-label"></label>                
               @* @Html.DropDownList("iller",(IEnumerable<SelectListItem>)ViewData["Illist"],"---Il Seciniz---");*@
                <select asp-for="IlId" class ="form-control" asp-items="ViewBag.IlId"></select>  
            </div>
            <div class="form-group">
                <label asp-for="IlceAd" class="control-label"></label>
                <input asp-for="IlceAd" class="form-control" /> 
                @if (ViewBag.Message != null && ViewBag.Message == "Exist")
        {
            <br /><span style="color:red;">Kayıt mevcut!!!</span>
        }
                <span asp-validation-for="IlceAd" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div> 
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

正如this document所说:

Beginning with .NET 6, new projects include the <Nullable>enable</Nullable> element in the project file. Once the feature is turned on, existing reference variable declarations become non-nullable reference types.

所以non-nullable属性必须在asp.net6中要求,否则ModelState会无效

要实现您的要求,您可以从项目文件中删除 <Nullable>enable</Nullable>

或者您可以像下面这样初始化数据:

public partial class Ilceler
{
    public Ilceler()
    {
        Il = new Iller();   //add here...
        //...
    }
    public int IlceId { get; set; }
    public int IlId { get; set; }
    public string IlceAd { get; set; } = null!;

    public virtual Iller Il { get; set; }
    //...
}

首先感谢您的帮助。我就是这样解决的。这是正确的方法吗?或者有没有更准确的方法?


 public async Task<IActionResult> Create([Bind("IlceId,IlId,IlceAd")] Ilceler ilceler)
        {
            Iller Il = new Iller();
            Il = _context.Illers.Find(ilceler.IlId); 

            if (ModelState.IsValid)
            {
                var ilce = _context.Ilcelers.Where(x => x.IlceAd == ilceler.IlceAd).FirstOrDefault();
                if (ilce != null)
                {
                    ViewBag.Message = "Exist";
                    return View();
                }
                else
                {
                    _context.Add(ilceler);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
            }
            ViewData["IlId"] = new SelectList(await _context.Illers.ToListAsync(), "IlId", "IlAd");