Home > Net >  Problem when submit a form with select tag helper asp.net core 6
Problem when submit a form with select tag helper asp.net core 6

Time:02-27

I want to use select tag helper to choose a role for creating account in my web app.

The following is my code

[HttpGet]
    public ActionResult Create()
    {
        var model = new AccountCreateViewModel()
        {
            Roles = new SelectList(_roleManager.Roles, "Id", "Name").ToList()
        };

        return View(model);
    }

The following is the code in view of the select.

<div >
    <select asp-for="RoleId" asp-items="@Model.Roles" ></select>
    <label asp-for="RoleId"></label>
    <span asp-validation-for="RoleId" ></span>
</div>

<input type="submit"  />

The following is my model

public class AccountCreateViewModel
{
    public RegisterModel.InputModel Input { get; set; } = new();

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

    [DataType(DataType.Date)]
    public DateTime? BirthDate { get; set; } = null;

    [StringLength(80)]
    public string Address { get; set; }

    [Required]
    [Display(Name = "Role")]
    public string RoleId { get; set; }
    
    public List<SelectListItem> Roles { get; set; }
}

However, after I submit the form, then the controller check the model state, and it is invalid. I have debugged and all the fields is valid except Roles. So, someone can give me a solution for this situation?

model state debugging

CodePudding user response:

Apply [ValidateNever] attribute to remove validate of the Roles on the server side. When applied to a property, the validation system excludes that property.

public class AccountCreateViewModel
{
    ...
    [ValidateNever]
    public List<SelectListItem> Roles { get; set; }
}

CodePudding user response:

Consider that a SelectList takes an object of type IEnumerable as the first argument in the constructor. Ensure that you give it an IEnumerable or List in this section:

Roles = new SelectList(_roleManager.Roles, "Id", "Name").ToList()

This code may help you:

Roles = new SelectList(_roleManager.Roles.ToList(), "Id", "Name")

If _roleManager.Roles returns an IEnumerable or List, you don't need the .ToList()

  • Related