MVC Razor HTML表单验证不捕获错误怎么办?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (161)

我试图制作一个简单的表单,它接受两个必需的输入和一个可选的输入 。

提交时会出现问题。验证是完全跳过的,不管我在框中放了什么,它总是直接指向方法,并且不向用户显示任何验证文本。此外,模型状态始终有效。

代码如下:
@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");
}

扫码关注云+社区

领取腾讯云代金券