How enable or disable Entity validation
I use Entity Framework 4 and MVC 2.
I Have an Address Entity, Contact, Company. There are a relation between Contact and Address and Company and Address.. A Contact can Have an Address and a Company can also have an 开发者_运维技巧address too.I created a Partial View for Address.
<div class="editor">
<%: Html.HiddenFor(model => model.AddressID) %>
<%: Html.HiddenFor(model => model.AddressID) %>
<div class="editor-label">
<%: Html.LabelFor(model => model.CivicNumber) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.CivicNumber)%>
<%: Html.ValidationMessageFor(model => model.CivicNumber)%>
</div>
</div>
<div class="editor">
<div class="editor-label">
<%: Html.LabelFor(model => model.Street) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Street)%>
<%: Html.ValidationMessageFor(model => model.Street)%>
</div>
</div> ......
I Call this Partial view in my Contact and Company View with EditorFor.
In the Address Class, I had some validation.
Example : The Civic Number is required.[Required(ErrorMessage = "Civic Number is Required")]
[DisplayName("Civic Number")]
public object CivicNumber { get; set; }
Is it possible to Active this validation only when I Call Address from Contact. In other words. If I Call the Address.ascx from Company View I Don't want any validation for Address Fields. If I Call the Address.ascx from Contact View, I want the validation for Address Fields.
Hope someone will understand.
ThanksI am not completely sure but give it a shot.
In your partial view
<% bool outputValidation = this.ViewContext.Controller.ViewData.Model.GetType() == typeof(Contact) %>
<div class="editor">
<%: Html.HiddenFor(model => model.AddressID) %>
<%: Html.HiddenFor(model => model.AddressID) %>
<div class="editor-label">
<%: Html.LabelFor(model => model.CivicNumber) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.CivicNumber)%>
<%: outputValidation ? Html.ValidationMessageFor(model => model.CivicNumber) : "" %>
</div>
</div>
What you are doing is getting the Model of the parent view. Then just check it's type.
精彩评论