简体   繁体   中英

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

I tried to create Order object in my project. 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). I am using Microsoft Visual Studio 2022 and template of 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

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

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

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

@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

  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
<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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