我在 ASP.NET Core MVC 应用程序中遇到模型绑定问题。目前,MVC 模板是默认模板。当我编写 HTTP POST 方法时,用户提交反馈后,它不会存储在反馈对象中:
public async Task<IActionResult> Feedback(FeedbackModel feedback)
HomeController
public IActionResult Feedback()
{
return View("Feedback");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Feedback(FeedbackModel feedback)
{
if (!ModelState.IsValid)
{
// Log or inspect model state errors
foreach (var error in ModelState.Values.SelectMany(v => v.Errors))
{
_logger.LogError($"Error: {error.ErrorMessage}");
}
return View(feedback);
}
var jsonFeedback = JsonConvert.SerializeObject(feedback);
var deserializedFeedback = JsonConvert.DeserializeObject<object>(jsonFeedback, new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
});
string filePath = "feedback.txt";
await System.IO.File.WriteAllTextAsync(filePath, jsonFeedback);
return RedirectToAction("Index");
}
View
@model FeedbackModel
@{
ViewData["Title"] = "Feedback";
}
<h2>@ViewData["Title"]</h2>
@if (TempData["Message"] != null)
{
<div class="alert alert-success">
@TempData["Message"]
</div>
}
<form method="post" >
<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="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Feedback" class="control-label"></label>
<textarea asp-for="Feedback" class="form-control"></textarea>
<span asp-validation-for="Feedback" class="text-danger"></span>
</div>
<button type="submit" asp-controller="Home" class="btn btn-primary">Submit</button>
</form>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Model
using System.ComponentModel.DataAnnotations;
namespace SecureStoreApp.Models
{
public class FeedbackModel
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Feedback is required")]
public string Feedback { get; set; }
}
}
你的模型
FeedbackModel
有属性FeedBack
,并且你设置的绑定参数名称是feedback
,导致冲突
“FeedbackModel”类型的属性与参数“feedback”同名。这可能会导致模型绑定不正确。考虑重命名参数或属性以避免冲突。如果类型“FeedbackModel”具有自定义类型转换器或自定义模型绑定器,您可以抑制此消息。
您应该重命名以避免冲突,我建议将
feedback
重命名为 model
,它应该可以工作。
[ValidateAntiForgeryToken]
// Rename feedback to model
public async Task<IActionResult> Feedback(FeedbackModel model)
{
if (!ModelState.IsValid)