[英]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 个选择
public string? Name { get; set; }
public string? Address { get; set; }
public string? Phone { get; set; }
... and so on
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<!--<Nullable>enable</Nullable>-->
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.