【发布时间】:2019-03-04 04:06:40
【问题描述】:
我在使用表单返回模型时遇到问题。
问题是当我提交表单时,即使我指定了返回模型,这些值也为空
这是我的控制器
这是我返回 null 的视图。
@model MyEnglishDictionary.Models.Dictionary
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form method="post" asp-action="Create">
<div class="p-4 border rounded">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Word"></label>
</div>
<div class="col-5">
<input asp-for="Word" class="form-control" />
</div>
<span asp-validation-for="Word" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Meaning"></label>
</div>
<div class="col-5">
<input asp-for="Meaning" class="form-control" />
</div>
<span asp-validation-for="Meaning" class="text-danger"></span>
</div>
<div class="form-group row">
<div class="col-2">
<label asp-for="Pronunciation"></label>
</div>
<div class="col-5">
<input asp-for="Pronunciation" class="form-control" />
</div>
<span asp-validation-for="Pronunciation" class="text-danger"></span>
</div>
<br />
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Create" />
<a asp-action="Index" class="btn btn-success">Back To List</a>
</div>
</div>
</form>
@section Scripts{
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
编辑
这是我的字典控制器。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MyEnglishDictionary.Data;
using MyEnglishDictionary.Models;
namespace MyEnglishDictionary.Controllers
{
public class DictionaryController : Controller
{
private readonly ApplicationDbContext _db;
public DictionaryController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return View(_db.Dictionaries.ToList());
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Models.Dictionary word)
{
if(!ModelState.IsValid)
{
return View(word);
}
_db.Add(word);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}
这是我的字典模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyEnglishDictionary.Models
{
public class Dictionary
{
[Key]
public int Id { get; set; }
[Required]
public string Word { get; set; }
[Required]
public string Meaning { get; set; }
[Required]
public string Pronunciation { get; set; }
public string Link { get; set; }
public DateTime Date { get; set; }
}
}
我使用的是 Net Core 2.1,但我有一些项目使用相同的方式将表单模型从视图传递到控制器并且它们可以工作。
【问题讨论】:
-
可能你没有为你的模型添加绑定属性
[BindProperty],你能把你的控制器发布到问题中而不是图片。 -
你的@Html.AntiForgeryToken() 方法在哪里?
-
@FatikhanGasimov 使用 Asp.Net Core 2 或更高版本,表单标签会自动将防伪令牌注入 html 表单元素,请参阅文档 here
-
您应该在答案中发布您的控制器代码而不是屏幕截图,这对于试图帮助您的人来说更难
-
可以加你
Dictionary类吗?
标签: c# .net asp.net-core asp.net-core-mvc