如果另一个字段不为null,则实现Require验证的最佳方法

时间:2014-04-24 14:23:22

标签: asp.net asp.net-mvc asp.net-mvc-4 ivalidatableobject

我的视图中有以下两个字段: -

<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) | 

我想要实现的规则是两个字段都是NullAble,但是如果用户选择了ConsoleServerID,那么他需要添加一个端口。如果用户将ConsoleServerID保留为null,则不应输入端口号。 那么实现这种情况的最佳方法是什么,以便我同时进行客户端和服务器端验证? 感谢

修改 安装万无一失后,我面临以下问题: -

  1. 没有实现客户端验证,并且在检查模型状态在我的控制器类中是否有效时正在实施验证

  2. 如果[RequiredIfNotEmpty]为false,则suer将返回以下消息: - 由于ConsoleServerID不为空,因此需要控制台服务器端口。那么为什么将显示ConsoleServerID而不是控制台服务器的字段名称标签

  3. 如果用户尝试提交ConsoleServerID为null的表单,那么我将接收以下异常: -

  4.   

    System.Data.Entity.Validation.DbUnexpectedValidationException是   用户代码未处理HResult = -2146233087消息=意外   在验证“控制台服务器端口”时抛出异常   调用Foolproof.RequiredIfNotEmptyAttribute.IsValid。看到内心   细节例外。 Source = EntityFramework StackTrace:          at System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext)   entityValidationContext,InternalMemberEntry属性)          在System.Data.Entity.Internal.Validation.PropertyValidator.Validate(EntityValidationContext)   entityValidationContext,InternalMemberEntry属性)          在System.Data.Entity.Internal.Validation.EntityValidator.ValidateProperties(EntityValidationContext)   entityValidationContext,InternalPropertyEntry parentProperty,List 1 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(IDictionary 2   项)          在System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry,IDictionary 2 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, IDictionary 2个参数)          在System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext   controllerContext,ActionDescriptor actionDescriptor,IDictionary 2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8 1.b__7(IAsyncResult)   _)          在System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()          在System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult)   asyncResult)          在System.Web.Mvc.Async.AsyncControllerActionInvoker。&lt;&gt; c__DisplayClass37。&lt;&gt; c__DisplayClass39.b__33()          在System.Web.Mvc.Async.AsyncControllerActionInvoker。&lt;&gt; c__DisplayClass4f.b__49()   InnerException:System.NotImplementedException          的HResult = -2147467263          Message =未实现方法或操作。          来源= MVC万无一失的验证          堆栈跟踪:               在Foolproof.ModelAwareValidationAttribute.IsValid(对象值)               在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属性)          的InnerException:

2 个答案:

答案 0 :(得分:1)

我们做了很多ajax调用。我如何触发客户端验证是

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

form.valid触发表单上的验证

答案 1 :(得分:1)

最好的方法是将该逻辑放在模型中

在您的ViewModel中,创建一个像这样的bool propery:

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

然后,使用您的RequiredIf属性,如下所示:

[RequiredIf("IsAddingPortRequired", true, ErrorMessage = "You must add a port Number")]