我正在尝试制作一个简单的表单,该表单接受两个必需的输入和一个可选的输入(还具有一个“隐藏”属性-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>
}
ViewModel
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");
}
答案 0 :(得分:1)
一个简单的答案...要做的就是不要将每个参数分别传递给控制器方法,而只需传递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的主视图。部分视图。