Razor: @Html.HiddenFor() need to turn off validation
Could you help me, please.
I have a class:
public class Product
{
...
// NOT REQUIRED!
public virtual Category Category{ get; set; }
}
But when in a view I create
@Html.HiddenFor(model => model.Category.Id), or
@Html.Hidden("model.Category.Id", model => model.Category.Id)
razor adds validation attribute to this.
- How to turn it off? (in model, in view)
- How to turn off validation event if a property has the attribute [Required]?
I found out that this is not a razor problem, it is somewhere in MV开发者_JS百科C. Even if I manage to pass "Category.Id" value = "" to the server, TryModelUpdate() will fail - it requires "Category.Id" to be set, but it's not required in my model.
Why is it so??!
I solved the same issue with an crutch like this:
@{ Html.EnableUnobtrusiveJavaScript(false); }
@Html.HiddenFor(t => t.Prop1)
@Html.HiddenFor(t => t.Prop2)
...
@{ Html.EnableUnobtrusiveJavaScript(true); }
Setup a hidden like:
@Html.Hidden("CategoryIdHidden", model => model.Category.Id)
And process the posted hidden value separate from the model binding stuff... I think the validation is UI specific, and not model specific, so it wouldn't validate the category ID.
Or, supply in the hidden a default value of "0". A value of "" probably won't evaluate correctly if the category.ID is of type int, hence its null, hence it errors.
HTH.
精彩评论