2

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?

2
  • 1
    Why can't you use two different models? Commented Nov 24, 2011 at 13:59
  • I am facing same problem for so many view in my project. But its not fare to create each model for each view. so, i need to find a solution. Commented Nov 24, 2011 at 14:03

2 Answers 2

1

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" } );
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.