.NTE MVC how to make some of the properties to verify ModelState

In developing MVC, model validation is very common, should we use are all the usual verification of

if(ModelState.IsValid)
{
	//验证成功要做的事
	.....
}

But sometimes we need to verify the part, such as modifying the user information as updating user, not all users update information, so when the model is incomplete, and certainly will not be verified.
Here a model class, as an example

public class User
{
    [Required]
    public int ID { get; set; }

    [Required]
    [StringLength(18,MinimumLength = 2,ErrorMessage = "名称字符长度在2-18之间")]
    public string Name { get; set; }

    [Required]
    [Range(0,100,ErrorMessage = "年龄在0-100")]
    public int Age { get; set; }
}

Case 1: The term does not validate relatively small

We can use the Removemethod

//不验证年龄项
ModelState.Remove("Age");

Case 2: do relatively little to verify items

Unfortunately, I see the MSDN does not seem to find the method of this feature (if you find it, please leave a message comments area = =)
So now write an extension method to achieve this function

/// <summary>
/// 验证实体模型中的部分属性
/// </summary>
/// <param name="ModelState"></param>
/// <param name="keys">要验证的属性List集合</param>
/// <returns></returns>
public static bool IsPartValid(this ModelStateDictionary ModelState,List<string> keys)
{
    //遍历要验证部分属性
    foreach (var item in keys)
    {
        //尝试获取对应键的值
        //有不符合的模型属性 - Errors错误集合大于0
        if (ModelState.TryGetValue(item,out ModelState modelState) && modelState.Errors.Count > 0)          
            return false;
    }
    return true;
}

Then used directly, to want to verify it into a collection

//验证模型中的部分属性
if (ModelState.IsPartValid(new List<string> { "Name", "Age" }))
{
	//验证通过,要做的事
	......
}
Published 62 original articles · won praise 68 · views 160 000 +

Guess you like

Origin blog.csdn.net/ZUFE_ZXh/article/details/102600913