简体   繁体   English

在MVC中验证

[英]Validating in MVC

Hi i am a beginner in MVC i have written code for validating but it is not working can anyone please help me out. 嗨,我是MVC的初学者,我已经编写了用于验证的代码,但是它不能正常工作,任何人都可以帮助我。 Here is the model code: 这是模型代码:

[Required]
public string Name { get; set; }

Here is the View code: 这是查看代码:

            @Html.TextBoxFor(m => m.ContactDetailSubSections[i].Name)
            @Html.ValidationMessageFor(m=>m.ContactDetailSubSections[i].Name)

Thanks in advance for your help 在此先感谢您的帮助

First of all, you don't need any of JS libraries for ASP.NET MVC server validation. 首先,您不需要任何JS库即可进行ASP.NET MVC服务器验证。
Second, you should check in controller, that a model is valid. 其次,您应该在控制器中检查模型是否有效。

if (ModelState.IsValid) {
    //do something
}
return View(); //you can return view with optional parameters

Also, you should check which Method for sending data are you use (POST or GET) and check that this method is used in controller (for sending data always use a POST method). 另外,您应该检查使用的是哪种发送数据的方法(POST或GET),并检查控制器中是否使用了此方法(对于发送数据,请始终使用POST方法)。

[HttpPost]
public ActionResult Index(YourModel model) {
    if (ModelState.IsValid) {
       //do something
    }
    return View();
}

This is the project for you (Validation.zip): http://sdrv.ms/UP3DIE (I'm using VS 2012) 这是适合您的项目(Validation.zip): http : //sdrv.ms/UP3DIE (我使用的是VS 2012)
There is only one field with Required attribute and custom error message (model LocalValidationTestModel). 只有一个字段具有Required属性和自定义错误消息(模型LocalValidationTestModel)。 And in the view there are two methods for displaying errors: 在视图中,有两种显示错误的方法:
@Html.ValidationSummary() and @Html.ValidationMessageFor(x => x.TestField) @ Html.ValidationSummary()和@ Html.ValidationMessageFor(x => x.TestField)

All JS scripts and CSS styles are cutted. 所有的JS脚本和CSS样式均被删除。

Also, why are you using arrays? 另外,为什么要使用数组?

I think you should reference several files of jquery . 我认为您应该引用jquery的几个文件。 and then in the action ,you must do something ,like this: 然后在操作中,您必须执行以下操作:

if(ModelState.IsValid) { //TODO } return View();

and the action must add attribute is [HttpPost] 并且必须添加的操作属性为[HttpPost]

You can use Enable Client side validation feature of MVC for standard validation which doesn't require any server side code in controller. 您可以使用MVC的启用客户端验证功能进行标准验证,该功能不需要控制器中的任何服务器端代码。

Enable Client side Validation 启用客户端验证

Enable Client side Validation-2 启用客户端验证2

However you also must check ModestState.IsValid() at controller level for better security. 但是,您还必须在控制器级别检查ModestState.IsValid(),以提高安全性。

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

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