Reputation: 2382
I have a model class "Country" with property "CultureId" that is NOT marked as required. Another class "CountryViewModel" holds the same property "CultureId".
When rendering the "Create" view, I noticed that validation data attributes were added to the "CultureId" textbox, although there were no data annotations added.
I am using
@Html.HiddenFor(mode => mode.CultureId)
What might be the cause for such a behavior?
Thanks
Upvotes: 6
Views: 8732
Reputation: 459
There are couple of ways to handle this -
a). Make the property as Nullable like
public int? Age { get; set; }
b). Use the below in controller class -
ModelState["Age"].Errors.Clear();
c). Add to the startup- DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
Upvotes: 9
Reputation: 9630
try this:
ModelState["CultureId"].Errors.Clear();
if (ModelState.IsValid)
{
.....
}
If CultureId is int then it will also give you the desired result...
Upvotes: 0
Reputation: 3268
I'm guessing your CultureId is an int. MVC automatically adds required tags to non-nullable value types.
To turn this off add
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
to Application_Start or make your int nullable
Upvotes: 12
Reputation: 250
if you can use data annotations, you should check out this http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute.aspx
namespace MvcApplication1.Models
{
[MetadataType(typeof(MovieMetaData))]
public partial class Movie
{
}
public class MovieMetaData
{
[Required]
public object Title { get; set; }
[Required]
[StringLength(5)]
public object Director { get; set; }
[DisplayName("Date Released")]
[Required]
public object DateReleased { get; set; }
}
}
it helps you set validations without models on database side.
Upvotes: 0