如何手动启用ASP.NET MVC jQuery验证 [英] How to manually enable jQuery validation with ASP.NET MVC

查看:114
本文介绍了如何手动启用ASP.NET MVC jQuery验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我挣扎了解一些jQuery验证的基础知识与ASP.NET MVC接线。我是一个有经验的程序员的.NET,但这是我在编写JavaScript的第一次尝试。我通过网上的教程和一些教科书走了,但有一些神奇的烤到ASP.NET MVC的我没有看到...

I'm struggling to understand some of the basics of jQuery validation as wired up with ASP.NET MVC. I'm an experienced .NET programmer, but this is my first attempt at writing JavaScript. I've gone through the online tutorials and a couple of textbooks, but there is some magic baked into ASP.NET MVC that I'm not seeing...

这个问题的简短版本是:什么魔法我缺少的,它允许通过@ html.EditorFor()制作完成的jQuery验证code,但不工作我试图线了我使用完全相同的HTML自己的jQuery验证?

The short version of this question is: What magic am I missing that allows the code produced by @html.EditorFor() to perform jQuery validation, but doesn't work I try to wire up my own jQuery validation using the exact same HTML?

作为一个学习锻炼(因为它模仿什么,我真的想在我的网站做的),我创建了一个新的MVC应用程序4在Visual Studio 2012年我添加了一个视图模型:

As a learning exercise (and because it mimics what I really want to do in my website) I created a new MVC 4 app in Visual Studio 2012. I added a view model:

using System.ComponentModel.DataAnnotations;
namespace ValidationTest.Models
{
    public class MyViewModel
    {
        [Required]
        public string MyStringValue { get; set; }
    }
}

和我修改意见\\首页\\ Index.cshtml创建表单基于这样我的视图模型:

and I modified Views\Home\Index.cshtml to create a form based on my view model like this:

@model ValidationTest.Models.MyViewModel
@using (Html.BeginForm(new { id = "MyForm" })) {
    @Html.LabelFor(m => m.MyStringValue)
    @Html.EditorFor(m => m.MyStringValue)
    @Html.ValidationMessageFor(m => m.MyStringValue)

    <br />
    <input type="submit" value="Submit" />
}

最后,我修改了主页控制器视图模型提供的形式和处理相关的POST,像这样的:

Finally, I modified the Home controller to supply the view model to the form and to handle the associated POST, like this:

using System.Web;
using System.Web.Mvc;
using ValidationTest.Models;

namespace ValidationTest.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            var viewModel = new MyViewModel();
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Index(MyViewModel viewModel)
        {
            if (!ModelState.IsValid) return View(viewModel);

            return RedirectToAction("About");
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";
            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }
    }
}

当我运行该项目,该网页显示一个文本框,并奇迹般地将验证,用户必须输入一个值。到目前为止好...

When I run the project, the web page displays a text box and magically validates that the user must enter a value. So far so good...

现在,我的实际应用程序是一个在线调查。它显示问题,并在征求基于脚本的答案。我的实际视图模型包含映射到问题的文本,由用户提供的值等视图模型还包含一个指定用户是否必须提供一个值(即,是否不是布尔必填属性的属性使在视野中的必需的验证)。好了,这意味着我需要基于视图模型Required属性移除在MyStringValue属性[必需]属性在我看来,模型和提供自己的验证魔法。

Now, my actual app is an online survey. It displays questions and solicits answers based on a script. My actual view model contains properties that map to the text of the question, the value supplied by the user, etc. The view model also contains a Boolean Required property that specifies whether or not the user must supply a value (i.e., whether or not to enable "required" validation in the View). Ok, so this means that I need to remove the [Required] attribute on the MyStringValue property in my view model and supply my own validation magic based on the Required property in the view model.

这是我迷路。在IE中,我可以看到,在示例应用程序(如上文所述)html.xxx调用@产生这个HTML表单:

This is where I get lost. In IE, I can see that the @html.xxx calls in the sample app (outlined above) produces this HTML for the form:

<label for="MyStringValue">MyStringValue</label>
<input  class="text-box single-line" 
        data-val="true" 
        data-val-required="The MyStringValue field is required." 
        id="MyStringValue" 
        name="MyStringValue" 
        type="text" 
        value="" />
<span data-valmsg-for="MyStringValue" data-valmsg-replace="true"></span>

但我看不出有任何的HTML显然引用了jQuery验证库页面上的其他地方,我也不看的JavaScript code,使验证,所以我不明白为什么这个工程在所有。

But I don't see any HTML elsewhere on the page that obviously references the jQuery-validation library, nor do I see the JavaScript code that enables validation, so I don't understand why this works at all.

此外,如果我删除[必填]属性,和硬code中的视图发出上述HTML(没有魔法@ html.xxx()调用),则没有验证发生在所有。

Furthermore, if I remove the [Required] attribute, and hard-code the View to emit the above HTML (without the magic @html.xxx() calls) then no validation happens at all.

我是什么失踪?

推荐答案

是的,我失去了一些东西真的很重要。

Yes, I was missing something really fundamental.

一个新的MVC 4项目创建的页面模板(_Layout.cshtml)包含页面月底code:

The page template (_Layout.cshtml) created for a new MVC 4 project contains this code at the end of the page:

        @Scripts.Render("~/bundles/jquery")
        @RenderSection("scripts", required: false)
    </body>
</html>

这$ C $中的c jQuery库拉(毕竟在页面上的HTML已由浏览器看到),然后使一个可选的节,可以由视图提供。这code做的不可以拉了jQuery验证库。

That code pulls in the jQuery library (after all of the HTML on the page has been seen by the browser) and then renders an optional "section" that can be supplied by the view. That code does not pull in the jQuery validation library.

ASP.NET MVC的验证工作没有jQuery验证,但所有的验证在服务器上完成。细心的观察者会注意到,曾经警告说,缺少的字符串值必须提供,客户端验证,使预警只需在得罪文本框中输入一个字符消失。但是,如果没有jQuery验证启用,输入在文本框中不会动态删除警告。

ASP.NET MVC validation works without jQuery validation, but all of the validation is done in the server. The careful observer will note that, once warned that a missing string value must be supplied, client-side validation makes the warning go away by simply entering a single character in the offended text box. But without jQuery validation enabled, typing into the text box doesn't dynamically remove the warning.

在为jQuery验证上转的单一视图,这code需要在视图的CSHTML文件的某个位置(风格上,它希望成为在文件的结尾,因为它将在显示在HTML的末尾):

In order to "turn on" jQuery validation for a single view, this code needs to reside somewhere in the view's cshtml file (stylistically, it wants to be at the end of the file since it will show up at the end of the HTML):

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

所以,简单的答案,我的问题是在我的意见\\首页\\ Index.cshtml文件的末尾添加上述code。这使得jQuery验证,魔法发生,并且数据-XXX属性不再忽略。生活是美好的。

So, the short answer to my question is to add the above code at the end of my Views\Home\Index.cshtml file. This enables jQuery validation, magic happens, and the data-xxx attributes are no longer ignored. Life is good.

这篇关于如何手动启用ASP.NET MVC jQuery验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆