[英]MVC Razor Html form validation not catching errors
我正在尝试制作一个简单的表单,该表单接受两个必需的输入和一个可选的输入(还具有一个“隐藏”的属性TaskId
并在加载时设置,并且在设置后不更改)。
提交时出现问题。 验证被完全跳过,无论我在框中输入什么内容,验证始终直接进入方法,并且不向用户显示任何验证文本。 此外,无论如何,ModelState始终有效。
发布文字而不是图片。 对不起,那个家伙。
视图
@model ScrumBoard.Models.ViewModels.UpdateTaskViewModel
@{
HtmlHelper.ClientValidationEnabled = true;
}
@using (Html.BeginForm("EditTask", "Dashboard", FormMethod.Post, new { @class = "px-4 py-3" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(o => o.TaskId)
<div class="form-group">
@Html.LabelFor(o => o.Title)
@Html.TextBoxFor(o => o.Title, new { @class = "form-control" })
@Html.ValidationMessageFor(o => o.Title)
</div>
<div class="form-group">
@Html.LabelFor(o => o.Description)
@Html.TextAreaFor(o => o.Description, new { @class = "form-control", rows = 3 })
@Html.ValidationMessageFor(o => o.Description)
</div>
<div class="form-group">
@Html.LabelFor(o => o.Comment)
@Html.TextAreaFor(o => o.Comment, new { @class = "form-control", rows = 2, maxlength = 100 })
@Html.ValidationMessageFor(o => o.Description)
</div>
<button type="submit" class="btn btn-primary">Update</button>
}
视图模型
public class UpdateTaskViewModel
{
public UpdateTaskViewModel(int taskId)
{
TaskId = taskId;
}
public int TaskId { get; set; }
[Required(ErrorMessage = "Title is required", AllowEmptyStrings = false)]
[AllowHtml]
public string Title { get; set; }
[Required(ErrorMessage = "Description is required", AllowEmptyStrings = false)]
[AllowHtml]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[AllowHtml]
[DataType(DataType.MultilineText)]
public string Comment { get; set; }
}
调节器
[HttpPost]
public ActionResult EditTask(int taskId, string title, string description, string comment = "")
{
Alert alert;
if (ModelState.IsValid)
{
try
{
DatabaseOperations.UpdateTask(
taskId,
title,
description,
EacId,
comment);
alert = new Alert("Success!", "Updated task.", "alert-success");
}
catch (Exception e)
{
alert = new Alert("Error!", "Failed to update task.", "alert-danger", e);
}
}
else
{
alert = new Alert("Warning!", "ModelState is invalid.", "alert-warning");
}
TempData["Alert"] = alert;
return RedirectToAction("Index");
}
如此简单的答案...要做的就是不要将每个参数分别传递给控制器方法,而只需传递ViewModel即可,一切按预期进行:
[HttpPost]
public ActionResult EditTask(UpdateTaskViewModel model)
{
Alert alert;
if (ModelState.IsValid)
{
try
{
DatabaseOperations.UpdateTask(
model.TaskId,
model.Title,
model.Description,
EacId,
model.Comment);
alert = new Alert("Success!", "Updated task.", "alert-success");
}
catch (Exception e)
{
alert = new Alert("Error!", "Failed to update task.", "alert-danger", e);
}
}
else
{
return PartialView("_UpdateTask")
}
TempData["Alert"] = alert;
return RedirectToAction("Index");
}
PS。 因为这是我用来生成表单的局部视图,所以我需要将带有错误编辑模型的局部视图发回给我刚刚在@using(Html.BeginForm(...))
用部分视图替换html。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.