在MVC2文本框验证 [英] Textbox validation in MVC2

查看:116
本文介绍了在MVC2文本框验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加必需属性到我的模型类的属性之一,如下所示 -

I have added Required attribute to one of my properties of Model class as follows -

[Required(ErrorMessage="UserID should not be blank")]
[DisplayName("User Name")]
public string UserName { get; set; }

在我看来,它继承包含上述属性的类,我曾尝试申请validaton到一个文本框如下: -

Inside my view, which inherits the class containing above property, I have tried to apply validaton to a textbox as follows -

 <%= Html.TextBoxFor(model => Model.UserName, new { @class = "login-input",       @name="UserName" })%>
 <%= Html.ValidationMessageFor(model => Model.UserName)%>

但是当我运行这个程序,并调用后(使用按钮点击),无需输入在文本框中任何东西;我不明白的文本框验证?

But when I run this app, and invokes the post(using a button click), without entering anything in the textbox; I don't get the text box validated?

谁能告诉我什么,可能是被禁止的文本框验证的原因?

Can anyone please tell me what may be the reason that is prohibiting the textbox validation?

在此先感谢,
KAPS

Thanks in advance, kaps

推荐答案

这将只有HttpPost操作方法使用类(包含属性用户名)作为输入参数之一工作。

This will work only if the HttpPost Action method takes the class (which contains the property UserName) as one of its input parameters.

所以,如果你的code是这样的:

So if your code is something like this:

public class User
{
  public User() { } // Make sure the class has an empty constructor

  [Required(AllowEmptyStrings = false, ErrorMessage="UserID should not be blank")] 
  [DisplayName("User Name")] 
  public string UserName { get; set; } 
}

那么下面的操作方法将验证用户名:

Then the following action method will validate UserName:

[HttpPost]
public ActionResult AddUser(User user)
{ 
  ...
}

如果你的操作方法是这样的,它不会考虑您的验证属性:

If your action method is something like this, it will NOT consider your validation attributes:

[HttpPost]
public ActionResult AddUser(string userName)
{ 
  ...
}

此外,模式=&GT; Model.UserName 模式=&GT; model.UserName 不有所作为。

这篇关于在MVC2文本框验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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