简体   繁体   English

MVC中的JQuery必需的文本框验证和错误消息

[英]JQuery Required TextBox Validation and Error Message in MVC

I apologize in advance if this seems like a stupid question but after doing quite a bit of searching around I either can't put the right pieces together or simply haven't found the right answer. 如果这看起来像是一个愚蠢的问题,我先向您道歉,但经过大量的搜索后,我要么无法将正确的内容拼凑在一起,要么根本找不到正确的答案。 Anyways, I've got this model: 无论如何,我有这个模型:

public class Resort
{
    public int ID { get; set; }
    public String Name { get; set; }
    public int BlackDiamond { get; set; }
    public int BlueSquare { get; set; }
    public int GreenCircle { get; set; }
    public int TerrainPark { get; set; }
}

And I've got a view that creates TextBoxes as the input for each of those variables. 我有一个视图,该视图创建TextBoxes作为每个这些变量的输入。 What I need to do is set up some JQuery validation to ensure that each TextBox has a value in it, and more specifically that the TextBoxes for the int has numbers in it. 我需要做的是设置一些JQuery验证,以确保每个TextBox中都具有一个值,更具体地说,该int的TextBoxes中具有数字。

After doing a little research I'm just not sure how I can even go about setting up the script for the view or if I should rely on Data Annotations in the model?? 经过一些研究后,我只是不确定该如何为视图设置脚本,或者是否应该依赖模型中的数据注释? Any help is appreciated even if it is simply to point me in the right direction of research, I am here to learn. 即使只是为了指出正确的研究方向,我也会在这里学习,能为您提供任何帮助。 Thank you. 谢谢。

If it's a required field, add the RequiredAttribute to the field: 如果这是必填字段,则将RequiredAttribute添加到该字段:

[Required]
public int BlackDiamond { get; set; }

If you also want a custom message, add it to the attribute: 如果还需要自定义消息,请将其添加到属性中:

[Required(ErrorMessage="Please enter a number")]
public int BlackDiamond { get; set; }

If you want built-in jQuery validation, make sure you use the strongly-typed helper: 如果要内置jQuery验证,请确保使用强类型的帮助器:

@Html.TextBoxFor(m => m.BlackDiamond) // you can also use EditorFor

You will need to also include script references to the UnobtrusiveValidation and jQuery Validate plugins to get the automatic validation. 您还需要包括对UnobtrusiveValidation和jQuery Validate插件的脚本引用,以获得自动验证。

Just FYI, this seems like a good place to start, if you are unfamiliar with validation in MVC: http://msdn.microsoft.com/en-us/VS2010TrainingCourse_ASPNETMVC3FormsandValidation 仅供参考,如果您不熟悉MVC中的验证,那么这似乎是一个不错的起点: http : //msdn.microsoft.com/zh-cn/VS2010TrainingCourse_ASPNETMVC3FormsandValidation

EDIT: Just to make this answer a bit more complete, as noted in the comments: to see the error messages associated with each control, you need to add the validation helpers: @Html.ValidationMessageFor(m => m.BlackDiamond) 编辑:只是为了使此答案更完整,如注释中所述:要查看与每个控件相关的错误消息,您需要添加验证助手: @Html.ValidationMessageFor(m => m.BlackDiamond)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM