Swetha Bindu
Swetha Bindu

Reputation: 649

ASP.NET MVC3 Model Validations

I am using the same model for two views in ASP.NET MVC3 Razor. For example, I had a text box named "First Name". I need validation for this textbox only in one view and not in the other view. I know how to implement this in jquery, but my requirement is different in that, I had to differentiate it either in model or in the action of the particular view.

Some thing like:

[Required(ErrorMessage="First Name is Required")]
public string FirstName { get; set; }

But I'm unable to find out how to differentiate validation for two views in the same model.

Can someone please help me with this?

Upvotes: 2

Views: 298

Answers (2)

Paul
Paul

Reputation: 5576

Your views have different concerns and as such, two view models are probably appropriate in this case. Failing this I think you may need to put your validation elsewhere i.e. don't add the validation attribute on the view model, but check in the controller method...

if(string.IsNullOrEmpty(viewmodel.FirstName))
{
    ViewState.AddError("FirstName", "Required");
}

or similar

Upvotes: 1

Christiaan Nieuwlaat
Christiaan Nieuwlaat

Reputation: 1359

If you really want to do it without different (view)models, you can place the appropriate attributes on the input tag to get the validation done instead of specifying it on the model.

if you need the requirement in the above way you can do this: ( assuming you use razor syntax and unobtrusive validation )

@Html.TextboxFor(m=>m.FirstName, new { data_val="true", data_val_required="First name is required" } );

Upvotes: 1

Related Questions