How to manually validate a model with attributes?

前端 未结 4 1344
既然无缘
既然无缘 2020-12-02 14:01

I have a class called User and a property Name

public class User
{
    [Required]
    public string Name { get; set; }
}

4条回答
  •  有刺的猬
    2020-12-02 14:59

    Since the question is asking specifically about ASP.NET MVC, you can use the TryValidateObject inside your Controller action.

    Your desired method overload is TryValidateModel(Object)

    Validates the specified model instance.

    Returns true if the model validation is successful; otherwise false.

    Your modified source code

    [HttpPost]
    public ActionResult NewUser(UserViewModel userVM)
    {
        User u = new User();
        u.Name = null;
    
        if (this.TryValidateObject(u))
        {
            TempData["NewUserCreated"] = "New user created sucessfully";
            return RedirectToAction("Index");
        }
    
        return View();
    }
    

提交回复
热议问题