c# - 如何使用 microsoft ASP.NET MVC create 命令修复 http 错误 400
问题描述
我正在使用 Microsoft 教程设置第一个 C# ASP.NET MVC 应用程序。https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-2.2&tabs=visual-studio
在本教程的过程中,它要求检查创建电影是否有效,但是当我尝试使用它时,我收到 HTTP 错误 400 - 错误请求。我相信我输入的数据是准确的,但除了一个糟糕的请求,我似乎什么也得不到,有谁知道如何解决这个问题。
型号类:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MvcMovie.Models
{
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }
}
}
剃刀视图:
@model MvcMovie.Models.Movie
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Movie</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="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Genre" class="control-label"></label>
<input asp-for="Genre" class="form-control" />
<span asp-validation-for="Genre" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" 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");}
}
控制器动作方法:
public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(movie);
}
预期的输出是添加到数据库中,但实际输出是错误的请求。
解决方案
您是否有通过控制器方法的 httpPost 以及为什么不使用模型?
[HttpPost]
public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] ....
推荐阅读
- php - Laravel eloquent 关系查询多个
- ruby-on-rails -
Ruby on Rails 中的动态页面问题 - python - 每行的 Pandas DataFrame Rest Call
- php - 停用插件时如何删除2个表
- javascript - 错误 [Vue 警告]:不带参数的 v-bind 需要一个对象或数组值
- redis - Redis 时间序列数据建模
- database - Google Cloud SQL 数据库上的 pg_basebackup
- javascript - 自定义 vue.js 复选框绑定数组引发“避免直接改变道具......”我应该如何实现这个?
- c++ - 在 Ubuntu 中使用 C++ 将网络摄像头与 OpenCV 和 OpenGL 集成?
- c# - 是否可以从 GitHub 为基于 .NET Core Angular 模板的 Web 应用程序在 Azure 中设置持续集成?