如何使用 ViewModel 在 asp.net MVC 中正确验证表单?

How to properly validate a form in asp.net MVC with ViewModel?

I have been following the documentation here and here,但验证属性似乎不起作用。我的 RModel 中有这个:

[RegularExpression(@"^[A-Z]+[a-zA-Z'\s]*$")]
[Required]
[StringLength(10)]
public string FirstName { get; set; }

[Required]
[EmailAddress]
public string Email { get; set; }

我认为这是:

@using (Html.BeginForm("Index", "RHome", FormMethod.Post))
{
    <div class="field form-group col-sm-4">
        <input type="text" id="FirstName" placeholder=" ">
        <label for="FirstName">First Name</label>
        <span asp-validation-for="RModel.FirstName"></span>
    </div>

    <div class="field form-group col-sm-8">
        <input id="Email" placeholder=" ">
        <label for="Email">Email</label>
        <span asp-validation-for="RModel.Email"></span>
    </div>
    . . .
}

我正在使用 ViewModel 加载多个模型。其他模型与 RModel 非常相似。我不知道这是否会产生任何影响,但我认为可能会。

public class ViewModelR
{
    public RModel RModel { get; set; }
    public KnowledgeModel KnowledgeModel { get; set; }
}

我只想进行服务器端和客户端验证,以防止注入和不正确的输入等等。我该怎么做?

更新:我添加到我的视图,现在当我点击提交而不填写任何输入时,我似乎收到一条消息,暗示 [required] 正在工作。

The Email: field is required.
The First Name: field is required.

太好了,但我需要让所有其他验证正常工作,这样我才能防止错误的值?

我建议您对视图中的每个输入 html 元素使用验证消息脚手架。

@Html.ValidationMessageFor(model => model.RHome.FirstName, "", new { @class = "text-danger" })

我希望,您至少已经在您的视图中添加了以下 js。

jquery.validate.unobtrusive.js