MVC3 客户端验证——我缺少什么?

发布于 2024-12-14 22:54:31 字数 4036 浏览 3 评论 0 原文

我用谷歌搜索,查看了博客,在此处查看了多个答案...当我在 MVC3 应用程序中启用“客户端验证”时,验证仅在服务器上进行,而不是在客户端上进行 - 我的表单发布了必需的没有值的文本输入,只会在服务器上退回。

全面披露:在迄今为止我完成的 3 个 MVC 项目中,我从未让它能够一致且完全地工作。我确信我在这里遗漏了一些基本的东西,因为我发现绝大多数示例和操作方法都带有“本文指的是测试版”免责声明......

这通常是我感到沮丧和撕毁的地方所有“客户端的所有内容都必须是间接的和神奇的,因为我们害怕开发人员编写 javascript”垃圾并直接使用 jquery.validation ,但我想我会尝试在这里发帖,看看我是否遗漏了一些基本的东西。 ..就像我通常看起来的那样;)

这个模型:

public class RegisterModel
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string ConfirmPassword { get; set; }
}

这个视图(样式需要“textfield”类)​​:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.FirstName, "First Name is required.")
            @Html.TextBoxFor(model => model.FirstName, new { @class = "textfield" })
            @Html.LabelFor(model => model.FirstName, "First Name")


        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.LastName)
            @Html.TextBoxFor(model => model.LastName, new { @class = "textfield" })
            @Html.LabelFor(model => model.LastName, "Last Name")
        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.Email)
            @Html.TextBoxFor(model => model.Email, new { @class = "textfield" })
            @Html.LabelFor(model => model.Email, "Email Address")

        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.Password)
            @Html.PasswordFor(model => model.Password, new { @class = "textfield" })
            @Html.LabelFor(model => model.Password, "Password")

        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.ConfirmPassword)
            @Html.PasswordFor(model => model.ConfirmPassword, new { @class = "textfield" })
            @Html.LabelFor(model => model.ConfirmPassword, "Confirm")

        </div>

        <div class="form-item-right">
            <input type="submit" value="Sign Up!" class="buttonSignUp"/>
        </div>



}

这会产生如下标记:

            <span class="field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="false">First Name is required.</span>
            <input class="textfield" data-val="true" data-val-required="The FirstName field is required." id="FirstName" name="FirstName" value="" type="text">
            <label for="FirstName">First Name</label>

这些脚本通过布局视图包含:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js") "type="text/javascript"></script>

并且在 web.config 中:

<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

控制器代码的完整性:

    public ActionResult Candidate()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Candidate(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            //complete the registration

            return View("Confirm", new ConfirmationModel { Email = model.Email, FirstName = model.FirstName });   
        }
        else
        {
            return View(model);
        }
    }

视图中的所有结果这不会在客户端进行验证。表单发布时根本没有输入任何字段。验证仅在服务器上进行(FWIW 正常工作)。

怎么了?

编辑以包含视图中生成的标记。

I've googled, looked at blogs, checked out multiple answers here on SO... when I enable "Client Side Validation" in my MVC3 app, validation only takes place on the server, not the client -- my forms post with required text inputs that do not have values, only to be bounced at the server.

Full disclosure: I've never gotten this to work consistently and completely in any of the 3 MVC projects I've done so far. I'm convinced I'm missing something fundamental here, since the vast majority of the examples and how-to's I find carry "This article refers to beta release" disclaimers...

This is usually the point where I get frustrated and rip out all the "everything client side must be indirect and magic because we're afraid to have developers write javascript" garbage and just use jquery.validation directly, but I figured I'd try posting here to see if I'm missing something fundamental ... like I usually seem to be ;)

This Model:

public class RegisterModel
{
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string Password { get; set; }
    [Required]
    public string ConfirmPassword { get; set; }
}

This view (the "textfield" classes are needed for styling):

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.FirstName, "First Name is required.")
            @Html.TextBoxFor(model => model.FirstName, new { @class = "textfield" })
            @Html.LabelFor(model => model.FirstName, "First Name")


        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.LastName)
            @Html.TextBoxFor(model => model.LastName, new { @class = "textfield" })
            @Html.LabelFor(model => model.LastName, "Last Name")
        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.Email)
            @Html.TextBoxFor(model => model.Email, new { @class = "textfield" })
            @Html.LabelFor(model => model.Email, "Email Address")

        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.Password)
            @Html.PasswordFor(model => model.Password, new { @class = "textfield" })
            @Html.LabelFor(model => model.Password, "Password")

        </div>

        <div class="form-item-right">
            @Html.ValidationMessageFor(model => model.ConfirmPassword)
            @Html.PasswordFor(model => model.ConfirmPassword, new { @class = "textfield" })
            @Html.LabelFor(model => model.ConfirmPassword, "Confirm")

        </div>

        <div class="form-item-right">
            <input type="submit" value="Sign Up!" class="buttonSignUp"/>
        </div>



}

This results in markup like:

            <span class="field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="false">First Name is required.</span>
            <input class="textfield" data-val="true" data-val-required="The FirstName field is required." id="FirstName" name="FirstName" value="" type="text">
            <label for="FirstName">First Name</label>

These scripts included via a Layout view:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js") "type="text/javascript"></script>

And this in web.config:

<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

Controller code for completeness:

    public ActionResult Candidate()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Candidate(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            //complete the registration

            return View("Confirm", new ConfirmationModel { Email = model.Email, FirstName = model.FirstName });   
        }
        else
        {
            return View(model);
        }
    }

All results in a view that does no validation on the client side. The form posts with no fields entered at all. Validation only takes place at the server (which works correctly FWIW).

What's wrong?

Edit to include resulting markup from the view.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃扇骨 2024-12-21 22:54:31

我不知道您做错了什么,但您可以遵循以下简单步骤:

  1. 使用默认模板创建一个新的 ASP.NET MVC 3 项目
  2. 定义以下模型:

    公共类MyViewModel
    {
        [必需的]
        公共字符串 Foo { 得到;放; }
    }
    
  3. HomeController:

    公共类 HomeController :控制器
    {
        公共 ActionResult Index()
        {
            返回视图(new MyViewModel());
        }
    
        [http邮报]
        公共 ActionResult 索引(MyViewModel 模型)
        {
            返回视图(模型);
        }
    }
    
  4. 索引视图:

    <前><代码>@model MyViewModel

    ;

    @using(Html.BeginForm())
    {
    @Html.LabelFor(x => x.Foo)
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <按钮类型=“提交”>确定
    }

  5. 运行项目=>客户端和服务器端验证按预期工作

I don't know what you are doing wrong, but here are the easy steps you could follow:

  1. Create a new ASP.NET MVC 3 project using the default template
  2. Define the following model:

    public class MyViewModel
    {
        [Required]
        public string Foo { get; set; }
    }
    
  3. HomeController:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    
  4. Index view:

    @model MyViewModel
    
    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    
    @using (Html.BeginForm())
    {
        @Html.LabelFor(x => x.Foo)
        @Html.EditorFor(x => x.Foo)
        @Html.ValidationMessageFor(x => x.Foo)
        <button type="submit">OK</button>
    }
    
  5. Run the project => client side and server side validation work as expected

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文