0

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?

1
  • thanks for your reply.... but I am so sure that it is the only way out in my situation. Is there anything like ValidationProvider.Add(some property, some contraint) ? Commented Nov 26, 2012 at 16:25

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is not something I am looking for. I wanna bind a validation which mean it will work on the front end as well. The code here is forcefully push an error in the validation.
Okay - well it's always helpful to include that in the question ;) In short - yes - it can be done - but you will need to implement your own ModelMetadataProvider - I can't really give you code for that but I'm sure if you google around and read MVC articles and stuff you'll figure it out.
Andras, thanks for your reply. I really spend a good deal of time to google it. It will be great if you can post a link for that. I may search in a wrong direction.
sorry @KennethLam there's no ready-rolled solution I know of, and the code to do such a thing would simply take too long and make an answer that's too long to read. I strongly suggest getting hold of the MVC source, and looking at the existing provider to see how you can extend it.
0

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.

1 Comment

The logic needs to be in the controller.
0

You shouldn't because if you do, the attribute won't be required at the data layer and there will be no corresponding database constraint.

1 Comment

It has nothing to do with database. Model can be a custom create model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.