0

У меня возникла проблема с пользовательской проверкой в ​​ASP.NET MVC. Я хочу получить условную требуемую проверку для свойства ServerName ниже. Условие заключается в том, что свойство ServerSpecific имеет значение true, тогда имя_сервера должно быть обязательным. Я использовал метод Validate для этого, но по какой-то причине этот код Vlaidate methof никогда не попадает ни в какое условие. Здесь что-то не хватает?ASP.NET MVC Custom Validation (обязательно)

public class PlatformConfigurationEditModel : IValidatableObject 
{ 
    #region Constructor 
    public PlatformConfigurationEditModel() 
    { 
     SettingEnabled = true; 
    } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     if (ServerSpecific == true && String.IsNullOrEmpty(ServerName)) 
     { 
      yield return new ValidationResult("Please provide Server Name!."); 
     } 
    } 

    [ScaffoldColumn(false)] 
    public int Id { get; set; } 
    [Required] 

    [ScaffoldColumn(false)] 
    public int PlatformProfileId { get; set; } 

    [Required] 
    [ScaffoldColumn(false)] 
    public int EnvironmentId { get; set; } 

    [Required] 
    [DisplayName("Setting Name")] 
    [JqGridColumnEditable(true, EditType = JqGridColumnEditTypes.Text)] 
    public string SettingName { get; set; } 

    [Required] 
    [JqGridColumnEditable(true, EditType = JqGridColumnEditTypes.Text)] 
    [DisplayName("Setting Value")] 
    public string SettingValue { get; set; } 

    [Required] 
    [DisplayName("Setting Enabled")] 
    [JqGridColumnSearchable(false)] 
    [JqGridColumnEditable(true, EditType = JqGridColumnEditTypes.CheckBox)] 
    public bool SettingEnabled { get; set; } 

    [DisplayName("Server Specific")] 
    [JqGridColumnSearchable(false)] 
    [JqGridColumnEditable(true, EditType = JqGridColumnEditTypes.CheckBox)] 
    public Nullable<bool> ServerSpecific { get; set; } 


    [DisplayName("Server Name")] 
    [JqGridColumnEditable(true, "GetServers", "Profile", EditType = 
                JqGridColumnEditTypes.Select)] 
    public string ServerName { get; set; } 

    [ScaffoldColumn(false)] 
    public Nullable<int> ServerId { get; set; } 

    [ScaffoldColumn(false)] 
    public int ProfileVersionId { get; set; } 

    } 

}

Метод Действие контроллера

[HttpPost] 
    public ActionResult Add(
     [ModelBinder(typeof(PlatformConfigurationEditModelBinder))] 
     PlatformConfigurationEditModel platformconfiguration) 
    { 
     if (ModelState.IsValid) 
     { 
      #region web binding value adjustments 

      if (platformconfiguration.SettingName.ToLower() == "webbinding") 
      { 
       platformconfiguration.SettingValue = ModifyWebBinding 
       (platformconfiguration.SettingValue); 
      } 

      #endregion 

      var updatedEntity = From<PlatformConfigurationEditModel>.To<PlatformConfiguration> 
           (platformconfiguration); 
      //// 
      //// update server id 
      //// 

      if (updatedEntity.ServerSpecific.HasValue && updatedEntity.ServerSpecific.Value) 
      { 
       updatedEntity.ServerId = Convert.ToInt32(platformconfiguration.ServerName); 
      } 

      _context.PlatformConfigurations.Add(updatedEntity); 
      _context.SaveChanges(); 
     } 
     return RedirectToAction("Add"); 

    } 

Модель Binder-

public class PlatformConfigurationEditModelBinder : IModelBinder 
    { 
    public object BindModel(ControllerContext controllerContext, 
          ModelBindingContext bindingContext) 
    { 
     var request = controllerContext.HttpContext.Request; 
     int environmentId; 
     int profileId; 
     int id = 0; 
     int pfvid; 

     string paramdata = request.Params["Id"]; 

     if (!paramdata.Equals("_empty")) 
     { 
      int[] data = request.Params["id"].Split('-').Select(n => Convert.ToInt32(n)).ToArray 
      (); 
      id = data[0]; 
      profileId = data[1]; 
      environmentId = data[2]; 
      pfvid = data[3]; 
     } 
     else 
     { 
      id = 0; 
      int[] extdt = request.Params["ExtData"].Split('-').Select(n => Convert.ToInt32 
      (n)).ToArray(); 
      profileId = extdt[0]; 
      environmentId = extdt[1]; 
      pfvid = extdt[2]; 
     } 

     string settingEnabled = request.Params["SettingEnabled"]; 
     string serverSpecific = request.Params["ServerSpecific"]; 

     string settingName = request.Params["SettingName"]; 
     string settingValue = request.Params["SettingValue"]; 
     string serverName = request.Params["ServerName"]; 


     return new PlatformConfigurationEditModel 
      { 
       Id = id, 
       EnvironmentId = environmentId, 
       PlatformProfileId = profileId, 
       ServerSpecific = serverSpecific.ToLower() == "on" || serverSpecific.ToLower() 
       == "true", 
       SettingEnabled = settingEnabled.ToLower() == "on" || settingEnabled.ToLower() 
       == "true", 
       ServerName = serverName, 
       SettingName = settingName, 
       SettingValue = settingValue, 
       ProfileVersionId = pfvid 
      }; 
    } 
} 
+0

Вы уверены, что 'ServerSpecific == true'? –

+0

Вы пробовали FluentValidation? http://fluentvalidation.codeplex.com/ – John

+0

Вам нужно показать нам свой метод управления –

ответ

0

Я хотел бы сделать пользовательский модель связующего наследоваться от DefaulModelBinder вместо IModelBinder. Затем вызовите базовую реализацию в конце, после чего вы получите поддержку Validation.

Вы можете даже рассмотреть вопрос об использовании Джимми Богард в «Смарт Binder»

http://lostechies.com/jimmybogard/2009/03/18/a-better-model-binder/

Это позволяет создать массив модельных вяжущих, которые до сих пор все вызываете реализацию базового, когда они сделаны.

Имейте в виду, что Validate только вызывается после того, как все другие проверки были успешными. Это означает, что если у вас есть проверка на стороне клиента, эти проверки сначала потерпят неудачу. И пользователь должен будет исправить их до того, как будет вызван вызов IValidatableObject.Validate.

Еще один хороший ресурс эти две статьи:

http://odetocode.com/Blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx

http://odetocode.com/blogs/scott/archive/2009/05/05/iterating-on-an-asp-net-mvc-model-binder.aspx