1

我有一个看起来像这样的视图模型 -

public class upgradeViewModel
{
    public Cart Cart { get; set; }
    public RegisterModel RegisterModel { get; set; }
} 

视图模型包含一个名为模型对象的属性RegisterModelRegisterModel看起来与此类似 -

public class RegisterModel
{
    [Required]
    [Display(Name = "Your name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Your email address")]
    public string Email { get; set; }

    ...
}

我使用视图模型上的属性在使用对象作为模型RegisterModel的视图中设置表单。upgradeViewModel在提交表单时,我没有得到任何客户端验证,尽管我确实得到了RegisterModel对象的服务器端验证。

我相信我已经正确配置了所有内容,以便不显眼的客户端验证正常工作,并且它可以在网站的其他区域工作。我需要做一些额外的事情来让客户端验证为视图模型的子对象工作吗?

这是我的视图代码 -

@model upgradeViewModel

@{
    ViewBag.Title = "Title";
    Layout = "~/Views/Shared/_LayoutNormal.cshtml";
}

<h2>Title</h2>

Some text ....

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
    <div>
        <fieldset>
            <legend>Your Information</legend>

            <div class="editor-label">
                @Html.LabelFor(m => m.RegisterModel.UserName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.RegisterModel.UserName)
                @Html.ValidationMessageFor(m => m.RegisterModel.UserName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.RegisterModel.Email)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.RegisterModel.Email)
                @Html.ValidationMessageFor(m => m.RegisterModel.Email)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.RegisterModel.Password)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.RegisterModel.Password)
                @Html.ValidationMessageFor(m => m.RegisterModel.Password)
            </div>

            <div class="editor-label">
                @Html.LabelFor(m => m.RegisterModel.ConfirmPassword)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.RegisterModel.ConfirmPassword)
                @Html.ValidationMessageFor(m => m.RegisterModel.ConfirmPassword)
            </div>

            <p>
                <input type="submit" value="Save Details" class="inputbutton" />
            </p>
        </fieldset>
    </div>
}
4

1 回答 1

0

您应该确保以下 appsettings 在您的 web.config 文件中。你已经在你的页面上引用了 jquery.validate.unobtrusive.min.js 。(当你创建它时,它应该在你的 MVC 项目的 Scripts 文件夹中)

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
于 2012-10-26T14:07:11.667 回答