简体   繁体   中英

MVC3 Bind validation in controller

I spent a good amount of time on google and cannot find the answer.

Instead of having an attribute in the model class like

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

Can I add the Required requirement in the controller instead of attribute?

I am expecting something like ValidationProvider.Add(some model properties, some constraints) Have anyone done that before?

Yeah sure you can (in controller method):

if(string.IsNullOrWhiteSpace(model.Name))
  ModelState.AddModelError("Name", "Name is required");

if(!ModelState.IsValid)
  return View();

But really you should use the attributes, or implement IValidatableObject on your model class. Keeps things nicely separated.

If you can use HTML5 you can use the required attribute in the field itself (in the view). Also consider the FluentValidation for .Net (http://fluentvalidation.codeplex.com/). Or you can use knockoutjs framework to control required fields.

您不应该这样做,因为如果这样做,数据层将不需要该属性,并且不会有相应的数据库约束。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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