0

Am not sure if am repeating question but i didn't get exact answer for what am looking for

Am having strongly typed view which i bind from model

//Model

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

public bool isAllowed { get; set; }

Am allowing the only particular group of users to edit the sample based on the isAllowed Property

//View
if (Model.isAllowed)
{
    @Html.EditorFor(model => model.sample)
}

So now required field works if user is allowed but in other part validation fires there comes my problem.

How do i handle this and disable the required field for the other set of users ?

Or Does MVC have any standard in creating my view for this scenarios ?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Peru
  • 2,871
  • 5
  • 37
  • 66

2 Answers2

0

if I'm understanding the question correctly, you can render it as a hidden property if isAllowed is false, so your code should be something like this

if (Model.isAllowed)
{
    @Html.EditorFor(model => model.sample)
}
else
{
    @Html.HiddenFor(model => model.sample)
}
Mkh
  • 68
  • 1
  • 11
  • what if sample is empty ? i ll get required field validation no ? – Peru Apr 14 '14 at 06:39
  • You can assign a default value in this case @Html.HiddenFor(model => model.sample,new{value ="default value "})... Another way however strongly discouraged is to manually remove the error from the Modelstate object in your controller if Isallowed is false so it passes the IsValid check – Mkh Apr 14 '14 at 08:24
0

You are looking for RequiredIf validation attribute. You can start here:

http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx

And then if you want client side validation for it too you can look at this:

http://blogs.msdn.com/b/simonince/archive/2010/06/11/adding-client-side-script-to-an-mvc-conditional-validator.aspx

Similar question was asked here:

RequiredIf Conditional Validation Attribute

Community
  • 1
  • 1
Marko
  • 12,543
  • 10
  • 48
  • 58