简体   繁体   English

ModelState.IsValid 在 ASP.NET Core 6.0 MVC 中总是返回 false

[英]ModelState.IsValid always returns false in ASP.NET Core 6.0 MVC

I tried to create Order object in my project.我试图在我的项目中创建Order对象。 It keeps returning to the create page and didn't create the object.它一直返回到创建页面并且没有创建对象。 For the object itself has one to many relationship with Pembersih object (where Pembersih has many orders, while orders have only one pembersih).因为对象本身与 Pembersih 对象具有一对多的关系(其中 Pembersih 有许多订单,而订单只有一个 pembersih)。 I am using Microsoft Visual Studio 2022 and template of asp.net core web MVC 6.0.我正在使用 Microsoft Visual Studio 2022 和 asp.net core web MVC 6.0 的模板。 I tried modifying the controllers but it didn't work pls help me.我尝试修改控制器,但没有用,请帮助我。

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CarWash1.Models
{
    public class Order
    {
        [Key]
        public int OrderId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }

        public DateTime date { get; set; }
        [ForeignKey("PembersihId")]
        public int PembersihId { get; set; }
        public Pembersih pembersih { get; set; }
    }
}

Pembersih.cs彭伯西.cs

namespace CarWash1.Models
{
    public class Pembersih
    {
        public Pembersih(){
            orders = new List<Order>();
        }
        public int PembersihId { get; set; }
        public string PembersihName { get; set; }
        public string PembersihPhone { get; set; }
        public List<Order> orders { get; set; }
    }
}

OrdersController.cs OrdersController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using CarWash1.Data;
using CarWash1.Models;

namespace CarWash1.Controllers
{
    public class OrdersController : Controller
    {
        private readonly CarWash1Context _context;

        public OrdersController(CarWash1Context context)
        {
            _context = context;
        }

        // GET: Orders
        public async Task<IActionResult> Index()
        {
            var carWash1Context = _context.Order.Include(o => o.pembersih);
            return View(await carWash1Context.ToListAsync());
        }

        // GET: Orders/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Order == null)
            {
                return NotFound();
            }

            var order = await _context.Order
                .Include(o => o.pembersih)
                .FirstOrDefaultAsync(m => m.OrderId == id);
            if (order == null)
            {
                return NotFound();
            }

            return View(order);
        }

        // GET: Orders/Create
        public IActionResult Create()
        {
            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId");
            return View();
        }

        // POST: Orders/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("OrderId,Name,Address,Phone,PembersihId")] Order order)
        {
            if (ModelState.IsValid)
            {
                _context.Add(order);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId", order.PembersihId);
            return View(order);
        }

        // GET: Orders/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Order == null)
            {
                return NotFound();
            }

            var order = await _context.Order.FindAsync(id);
            if (order == null)
            {
                return NotFound();
            }
            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId", order.PembersihId);
            return View(order);
        }

        // POST: Orders/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("OrderId,Name,Address,Phone,PembersihId")] Order order)
        {
            if (id != order.OrderId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(order);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!OrderExists(order.OrderId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId", order.PembersihId);
            return View(order);
        }

        // GET: Orders/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Order == null)
            {
                return NotFound();
            }

            var order = await _context.Order
                .Include(o => o.pembersih)
                .FirstOrDefaultAsync(m => m.OrderId == id);
            if (order == null)
            {
                return NotFound();
            }

            return View(order);
        }

        // POST: Orders/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Order == null)
            {
                return Problem("Entity set 'CarWash1Context.Order'  is null.");
            }
            var order = await _context.Order.FindAsync(id);
            if (order != null)
            {
                _context.Order.Remove(order);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool OrderExists(int id)
        {
          return (_context.Order?.Any(e => e.OrderId == id)).GetValueOrDefault();
        }
    }
}

PembersihsController.cs PembersihsController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using CarWash1.Data;
using CarWash1.Models;

namespace CarWash1.Controllers
{
    public class PembersihsController : Controller
    {
        private readonly CarWash1Context _context;

        public PembersihsController(CarWash1Context context)
        {
            _context = context;
        }

        // GET: Pembersihs
        public async Task<IActionResult> Index()
        {
              return _context.Pembersih != null ? 
                          View(await _context.Pembersih.ToListAsync()) :
                          Problem("Entity set 'CarWash1Context.Pembersih'  is null.");
        }

        // GET: Pembersihs/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Pembersih == null)
            {
                return NotFound();
            }

            var pembersih = await _context.Pembersih
                .FirstOrDefaultAsync(m => m.PembersihId == id);
            if (pembersih == null)
            {
                return NotFound();
            }

            return View(pembersih);
        }

        // GET: Pembersihs/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Pembersihs/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("PembersihId,PembersihName,PembersihPhone")] Pembersih pembersih)
        {
            if (ModelState.IsValid)
            {
                _context.Add(pembersih);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(pembersih);
        }

        // GET: Pembersihs/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Pembersih == null)
            {
                return NotFound();
            }

            var pembersih = await _context.Pembersih.FindAsync(id);
            if (pembersih == null)
            {
                return NotFound();
            }
            return View(pembersih);
        }

        // POST: Pembersihs/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("PembersihId,PembersihName,PembersihPhone")] Pembersih pembersih)
        {
            if (id != pembersih.PembersihId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(pembersih);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PembersihExists(pembersih.PembersihId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(pembersih);
        }

        // GET: Pembersihs/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Pembersih == null)
            {
                return NotFound();
            }

            var pembersih = await _context.Pembersih
                .FirstOrDefaultAsync(m => m.PembersihId == id);
            if (pembersih == null)
            {
                return NotFound();
            }

            return View(pembersih);
        }

        // POST: Pembersihs/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Pembersih == null)
            {
                return Problem("Entity set 'CarWash1Context.Pembersih'  is null.");
            }
            var pembersih = await _context.Pembersih.FindAsync(id);
            if (pembersih != null)
            {
                _context.Pembersih.Remove(pembersih);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool PembersihExists(int id)
        {
          return (_context.Pembersih?.Any(e => e.PembersihId == id)).GetValueOrDefault();
        }
    }
}

Create.cshtml创建.cshtml

@model CarWash1.Models.Order

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

<h1>Create</h1>

<h4>Order</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="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Phone" class="control-label"></label>
                <input asp-for="Phone" class="form-control" />
                <span asp-validation-for="Phone" class="text-danger"></span>
            </div>
             <div class="form-group">
                <label asp-for="date" class="control-label"></label>
                <input asp-for="date" class="form-control" />
                <span asp-validation-for="date" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PembersihId" class="control-label"></label>
                <select asp-for="PembersihId" class ="form-control" asp-items="ViewBag.PembersihId"></select>
            </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");}
}

since you are using net 6.0 you have 2 choices由于您使用的是 net 6.0,因此您有 2 个选择

  1. Mark as nullable ALL properties in your ALL classes that not marked as required, for example将所有类中未标记为必需的所有属性标记为可为空,例如
        public string? Name { get; set; }
        public string? Address { get; set; }
        public string? Phone { get; set; }
        ... and so on
  1. OR change the project property Nullable , by commenting or removing or dissabling或通过评论或删除或禁用更改项目属性 Nullable
<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

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

相关问题 ASP.NET MVC 4是ModelState.IsValid,总是false - ASP.NET MVC 4 is ModelState.IsValid always false ASP.NET MVC 4 ModelState.IsValid始终为false - ASP.NET MVC 4 ModelState.IsValid is always false ASP.NET MVC 5 ModelState.IsValid在MVC中始终返回false - ASP.NET MVC 5 ModelState.IsValid is always returning false in MVC ASP.NET 5,MVC6,WebAPI - &gt; ModelState.IsValid始终返回true - ASP.NET 5, MVC6, WebAPI -> ModelState.IsValid always returns true 为什么ASP.NET上传图片时ModelState.IsValid总是返回false? - Why does ModelState.IsValid always return false when trying to upload an image in ASP.NET? 仅使用asp.net mvc4,modelstate.isvalid在编辑视图中返回false - modelstate.isvalid return false in edit view only using asp.net mvc4 由于 ASP.NET Core 中的 SelectList,ModelState.IsValid 一直为假 - ModelState.IsValid keeps being false because of SelectList in ASP.NET Core 带有JSON输入代码的ASP.NET MVC 5 ModelState.IsValid - ASP.NET MVC 5 ModelState.IsValid with json input code 使用RhinoMock在ASP.NET MVC中ModelState.IsValid的存根 - Stub for ModelState.IsValid in ASP.NET MVC using RhinoMock ASP.NET MVC,modelstate.isvalid从未以这种方式有效 - ASP.NET MVC, modelstate.isvalid is never valid this way
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM