In my user registry controller I have the following
[AllowAnonymous]
public ActionResult Register()
{
var categorias = db.Categoria.ToList().Where(x=>x.Estado);
var list = new SelectList(categorias, "Codigo", "Descripcion");
ViewData["categorias"] = list;
ViewBag.Drop= new SelectList(categorias, "Codigo", "Descripcion");
return View();
}
This correctly fills me a DropDownList
when loading the view. However, when I try to register, that is, when I try to save the data in the database, it gives me the following error:
The code to save to the database or method POST
is as follows:
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload)
{
ApplicationUser user = new ApplicationUser();
byte[] foto;
string categ = model.Categoria;
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
foto = reader.ReadBytes(upload.ContentLength);
}
user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
Hometown = model.Hometown,
Direccion = model.Direccion,
NombreComercial = model.NombreComercial,
Tipo = "Comercio",
Estado = true,
Foto = foto,
Link = model.Link,
Cedula = model.Cedula,
Categoria= categ
};
}
else
{
user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
Hometown = model.Hometown,
Direccion = model.Direccion,
NombreComercial = model.NombreComercial,
Tipo = "Comercio",
Estado = true,
Foto = model.Foto,
Link = model.Link,
Cedula = model.Cedula,
Categoria = categ
};
}
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
The problem you have is when you try to create the Model
UserManager.CreateAsync(user, model.Password)
without success .So your Register[HttpPost] Action returns you to the View
Register.cshtml
with the ModelRegisterViewModel
:Once in the View, it tries to create the but the with the categories
DropDownListFor()
no longer exists .ViewData["categorias"]
So you should recreate it before calling the View: