检查属性的模型状态

时间:2014-01-21 15:59:14

标签: c# asp.net-mvc-4

我的礼品控制器带有一个动作结果,该参数在参数tu中检查模型状态中的GiftViewModel。

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

GiftViewModel.cs:

    public class GiftViewModel
{

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

}

GiftController.cs

//
    // POST: /Gift/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(GiftViewModel model, string returnUrl)
    {
        // here instead of the overall modelstate
        // I would like to check only the modestate of the login property 
        // of my model
        if (ModelState.IsValid && WebSecurity.Login(model.login.Email, model.login.Password, persistCookie: model.login.RememberMe))
        {
            return View("Index", model);
        }

        return View("Index", model);
    }

我该如何管理?

4 个答案:

答案 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中实现。

答案 1 :(得分:2)

我做了一个模型状态扩展,这非常简单:

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

答案 2 :(得分: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);
}

答案 3 :(得分:0)

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

Simplest JQuery validation rules example

第二个也是更复杂的是为登录

创建自定义验证属性