本文介绍了从ModelState中验证删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号:

public class UserInfo
{
    public long ID { get; set; }

    [Required]
    [StringLength(50)]
    public string FirstName { get; set; }

    //...

    public bool Falg{ get; set; }
}

public class UserInfoExtra
{
    public long ID { get; set; }

    [Required]
    public string PhoneNumber { get; set; }

    //...
}

这两个模型被结合在一个ViewModel:

Those two models are combined in a ViewModel:

public class UserViewModel
{
    public UserInfo UserInfo { get; set; }
    public UserInfoExtra ExtraInfo { get; set; }
}

在控制器:

public ActionResult Create(UserViewModel userinfo)
{
    if(userInfo.Flag){
        //Remove ExtaInfo from validation in ModelState.IsValid?
    }
    if (ModelState.IsValid)
    {
        db.UserInfos.Add(userinfo);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(userinfo);
}

我怎样才能删除 ExtraInfo ModelState.IsValid

推荐答案

的ModelState 删除错误,是不是一个好主意。如果你不想让 UserInfoExtra 使用 UserViewModel ,那么你应该定义你的浏览模式时,可以验证类在******中国财产不同(如下图所示),然后用条件验证:

Removing errors from ModelState is not a good idea. If you don't want the UserInfoExtra class to be validated when using the UserViewModel, then you should define your View Model differently (like below), and then use conditional validation on the PhoneNumber property:

public class UserViewModel
{
    public UserInfo UserInfo { get; set; }
    public long ID { get; set; }
    //[RequiredIf] (conditional validation here)...
    public string PhoneNumber { get; set;}
}

在这里您可以找到 RequiredIf 属性的实现:RequiredIf有条件的验证属性

这篇关于从ModelState中验证删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 08:07