2014-01-21 67 views
0

我有我的礼品控制器的行为结果,它需要在参数tu中的GiftViewModel检查模型状态。检查模型状态的属性

我刚刚给GiftViewModel添加了一个LoginModel属性。我想测试这个属性的modelState。

GiftViewModel.cs:

public class GiftViewModel 
{ 

    public LoginModel login { get; set; } 
    [...] 

} 

GiftController.cs

​​

如何管理呢?

+1

为什么你需要吗?你会允许主视图模型的其他属性的无效值? –

+0

是的确切的说,我只想在其余的之前验证这个“步骤”。 – Cactus

+0

没有办法做到这一点。整个模型立即被验证。 –

回答

2

如果你想要做的是检查属性的有效性,有关使用方法如下:

var propertyToValidate = ModelState["PropertyName"]; 
if(propertyToValidate==null || //exclude if this could not happen or not to be counted as error 
    (propertyToValidate!=null && propertyToValidate.Errors.Any()) 
    ) 
{ 
    //Do what you want if this value is not valid 
} 
//Rest of code 

但请注意,在这种情况下,模型的其余部分已被验证。您只需在检查ModelState的其余部分之前检查此属性的有效性。如果您想先进行实际验证,那么必须在GiftViewModel的自定义ModelBinder中实施。

0

这样的事情呢?

public class GiftViewModel 
{ 

    public class LoginModel 
    { 
     [Required(ErrorMessage = "Email Required")] 
     RegularExpression(".+\\@.+\\..+", ErrorMessage = "You must type in a valid email address.")] 
     public string Email { get; set; } 

     [Required(ErrorMessage = "Password Required")] 
     public string password { get; set; } 
    } 

} 


public ActionResult Login(GiftViewModel model) 
{ 
     if(TryValidateModel(model)) 
     { 
     ///validated with all validations 
     } 

    return View("Index", model); 
} 
+0

不是真的,因为GiftViewModel可能具有其他无效的属性。我只想检查LoginModel属性的有效性。 – Cactus

+0

哎呀。有没有理由在服务器上进行而不是使用客户端验证?如果您确实想在服务器上执行此操作,那么您的LoginModel可以使用Validate方法实现IValidatableObject,您可以在其中放置验证代码。 – Sirentec

0

第一和最简单的解决方案是在验证(客户端)添加代码之前的结果被返回到服务器。

Simplest JQuery validation rules example

其次,更复杂的是创建一个自定义的验证属性的登录

1

我做了一个模型状态的扩展,这使得它可以很方便:

public static class ModelStateDictionaryExtensions 
{ 

    /// <summary> 
    /// Returns true when a model state validation error is found for the property provided 
    /// </summary> 
    /// <typeparam name="TModel">Model type to search</typeparam> 
    /// <typeparam name="TProp">Property type searching</typeparam> 
    /// <param name="expression">Property to search for</param> 
    /// <returns></returns> 
    public static bool HasErrorForProperty<TModel, TProp>(this System.Web.Mvc.ModelStateDictionary modelState, 
            Expression<Func<TModel, TProp>> expression) 
    { 
     var memberExpression = expression.Body as MemberExpression; 

     for (int i = 0; i < modelState.Keys.Count; i++) 
     { 
      if (modelState.Keys.ElementAt(i).Equals(memberExpression.Member.Name)) 
      { 

       return modelState.Values.ElementAt(i).Errors.Count > 0; 

      } 
     } 

     return false; 
    } 
} 

使用上面的方法,你只需输入:

if (ModelState.HasErrorForProperty<GiftViewModel, LoginModel >(e => e.login))