0

I have the following two fields inside my view:-

<div>

<span class="f">@Html.DisplayNameFor(model=>model.Firewall.ConsoleServerID)</span>

@Html.DropDownListFor(model =>model.Firewall.ConsoleServerID, ((IEnumerable<IT.Models.ITConsoleServer>)ViewBag.Servers).Select(option => new SelectListItem {
Text = (option == null ? "None" : option.Technology.Tag), 
Value = option.ConsoleServerID.ToString(),
Selected = (Model != null) && (Model.Firewall.ITConsoleServer != null) && (option.ConsoleServerID == Model.Firewall.ConsoleServerID)
}), "Choose...")
@Html.ValidationMessageFor(model =>model.Firewall.ConsoleServerID)

</div>

<div >
<span class="f">@Html.DisplayNameFor(model=>model.Firewall.ConsoleServerPort)</span> 

@Html.TextBoxFor(model => model.Firewall.ConsoleServerPort) 
@Html.ValidationMessageFor(model => model.Firewall.ConsoleServerPort) | 

The rule I want to implement is that both fields are NullAble, but if the user selects a ConsoleServerID , then he needs to add a Port . and if the user leave the ConsoleServerID null then he should not enter a Port number. So what is the best way to implement this scenario , so that I have both client side and server side validation ? Thanks

Edit After installing the foolproof i am facing the following problems :-

  1. no client side validation is being implemented, and the validation is being implemented when checking if the model state is valid inside my controller class

  2. if the [RequiredIfNotEmpty] is false then the suer will recive the following message:- Console Server Port is required due to ConsoleServerID not being empty .so why ConsoleServerID will be displayed instead of the field name which is Console Server Tag.

  3. if the user tried to submit the form where the ConsoleServerID is null then i will recevie the following exception :-

System.Data.Entity.Validation.DbUnexpectedValidationException was unhandled by user code HResult=-2146233087 Message=An unexpected exception was thrown during validation of 'Console Server Port' when invoking Foolproof.RequiredIfNotEmptyAttribute.IsValid. See the inner exception for details. Source=EntityFramework StackTrace: at System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) at System.Data.Entity.Internal.Validation.PropertyValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) at System.Data.Entity.Internal.Validation.EntityValidator.ValidateProperties(EntityValidationContext entityValidationContext, InternalPropertyEntry parentProperty, List1 validationErrors) at System.Data.Entity.Internal.Validation.TypeValidator.Validate(EntityValidationContext entityValidationContext, InternalPropertyEntry property) at System.Data.Entity.Internal.Validation.EntityValidator.Validate(EntityValidationContext entityValidationContext) at System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary2 items) at System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary2 items) at System.Data.Entity.DbContext.GetValidationErrors() at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at TMS.Models.Repository.Save() in c:\Users\Administrator\Desktop\New folder (19)\TMS\TMS\TMS\Models\Repository.cs:line 4614 at TMS.Controllers.FirewallController.Edit(FirewallJoin fj, FormCollection formValues) in c:\Users\Administrator\Desktop\New folder (19)\TMS\TMS\TMS\Controllers\FirewallController.cs:line 869 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass81.b__7(IAsyncResult _) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.b__33() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.b__49() InnerException: System.NotImplementedException HResult=-2147467263 Message=The method or operation is not implemented. Source=MVC Foolproof Validation StackTrace: at Foolproof.ModelAwareValidationAttribute.IsValid(Object value) at System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext) at System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext) at System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) InnerException:

John John
  • 1
  • 72
  • 238
  • 501
  • 1
    I like foolproof http://stackoverflow.com/questions/12843282/conditional-validation-in-asp-net-mvc4 – Matt Bodily Apr 24 '14 at 14:24
  • but will the foolproof also implement a server-side validation ?, so if a hacker by pass the client side validation, the fooproof should check the validation on the server ? – John John Apr 24 '14 at 15:07
  • 1
    yes it will. just do a if(ModelState.IsValid) on the controller and it will return false if your condition isn't met – Matt Bodily Apr 24 '14 at 15:08
  • i have installed the foolproof , and i add the following [RequiredIfNotEmpty("ConsoleServerID")] on the ConsoleServerPort, but i have noted that no client side validation will be done, all the validation will be done inside the controller ,, can you adivce – John John Apr 24 '14 at 15:33
  • also if the ConsoleServerId is null , then an exception will be raised .. – John John Apr 24 '14 at 15:45
  • you can add a display name attribute to the property on your model which should change your validation message to the name you are wanting. Hopefully the form.valid will fix the other issues once we can get that working – Matt Bodily Apr 24 '14 at 16:22
  • i already define a Display Name for the property, but seems that the foolproof did not recognize it .. – John John Apr 24 '14 at 16:28

2 Answers2

1

We do a lot of ajax calls. How I trigger the client side validation is

$('#btnClick').on('click', function(){
     if ($('form').valid()) {
         $.ajax({
         //call here
         });
     }
});

the form.valid triggers the validation on the form

Matt Bodily
  • 6,403
  • 4
  • 29
  • 48
  • but i need a more general approach which i can re-use all over the related views. the FoolProof is good but i am facing problem in using it.. – John John Apr 24 '14 at 16:01
  • 1
    it doesn't have to be an ajax call in the middle. Just set it up to trigger off of a button click or some other selector and run the form.valid. Make sure you have a form tag around the content you want validated – Matt Bodily Apr 24 '14 at 16:03
  • can you chekc my Edit please – John John Apr 24 '14 at 16:03
1

Best way would be to put that logic in your model

In your ViewModel, create a bool propery like this:

public bool IsAddingPortRequired
{
   get
   {
       return ConsoleServerID != null;
   }
}

Then, use your RequiredIf attribute like this:

[RequiredIf("IsAddingPortRequired", true, ErrorMessage = "You must add a port Number")]
meda
  • 45,103
  • 14
  • 92
  • 122
  • so why i can not use the foolproof instead? and where i need to create the ISAddingPortRequired ? inside the model class itself ? – John John Apr 24 '14 at 16:20
  • huh? `RequiredIf` **is** foolproof, as the builtin does not have this. yes put it right where you have `ConsoleServerID` – meda Apr 24 '14 at 16:22
  • aha ok sorry for that, but why i can not use [RequiredIfNotEmpty] then ? – John John Apr 24 '14 at 16:26
  • that im not sure (never tried it), maybe null and empty are not the same thing? – meda Apr 24 '14 at 16:29
  • @johnG did you get a chance to try it? it should solve your issue – meda Apr 24 '14 at 16:38