Search code examples
c#asp.netasp.net-mvcasp.net-core-mvcdata-annotations

Required attribute in action methods argument


I have an action method Create of a Controller as follows:

[HttpPost]
public async Task<IActionResult> Create([Required]string name)
{
    if (ModelState.IsValid)
    {
        IdentityResult result = await roleManager.CreateAsync(new IdentityRole(name));
        if (result.Succeeded)
            return RedirectToAction("Index");
        else
            Errors(result);
    }
    return View(name);
}

What does the [Required] attribute do here in argument?


Solution

  • The [Required] attribute allows you to use ModelState.IsValid construct.

    Basically it says that your model is invalid when the marked parameter is null.

    Reference: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.1