I am trying to create a registration form (view). Whenever I do a HTTP POST
with my model, I get an "Invalid ModelState" error on the 2 lists that I have in my view model. All properties are filled - the error is on the second list - not the data keyed!
I am using ASP.NET Core 9.0.2.
Here is my view model:
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Remote(action: "IsEmailInUse", controller: "Account")] // Remote validation
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password",
ErrorMessage = "Password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
public bool Terms { get; set; }
public List<SelectListItem> User_Types { get; internal set; }
[Display(Name = "Membership")]
public string User_Type { get; set; }
[Display(Name = "How Did You Hear About Us?")]
public String User_HDYHAU { get; set; }
public List<SelectListItem> List_HowDidYouHearAboutUs { get; internal set; }
}
Here is my controller - on the Post
, I am only showing the first few lines as the ModelState
shows invalid right away. Notice that I have tried to repopulate the 2 lists already:
[HttpGet]
[AllowAnonymous]
public IActionResult RegisterCreate()
{
var List_HDYHAU = GlobalHandlers.GetListOf_HDYHAU().ToList();
RegisterViewModel model = new RegisterViewModel()
{
User_Types = (from c in GlobalHandlers.GetListOf_Roles().ToList()
select new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
{ Value = c.Key, Text = c.Value }).ToList(),
List_HowDidYouHearAboutUs = (from c in List_HDYHAU
select new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
{ Value = c.Key, Text = c.Value }).ToList(),
};
return View(model);
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> RegisterCreate(RegisterViewModel model)
{
var List_HDYHAU = GlobalHandlers.GetListOf_HDYHAU().ToList();
model.List_HowDidYouHearAboutUs = (from c in List_HDYHAU
select new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
{ Value = c.Key, Text = c.Value }).ToList();
model.User_Types = (from c in GlobalHandlers.GetListOf_Roles().ToList() select new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem { Value = c.Key, Text = c.Value }).ToList();
bool errorExists = false;
if (ModelState.IsValid)
{
// .....MORE CODE HERE
}
}
What am I missing ? Thank you very much.
I tried to repopulate the 2 lists on the post and update the model, but that is not working.