DropDownList with Selected Me returns Null when doing post

0

I am working with ASP.Net MVC 5 and EF6, I have a class to edit users of the application and fill in a DropDownList the roles that exist and has preselected the role of the user, when doing post selecting another Role returns me a exception in the null view

  

Model.RolesList = 'Model.RolesList' started a type exception   'System.NullReferenceException'

This is the driver that brings the user's data to edit:

public ActionResult Edit(string Id)
    {
        //var Usuario = ctx.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
        var Usuario = UserManager.FindById(Id);

        var UsuarioRol = UserManager.GetRoles(Id).First();

        return View(new EditUsuarioViewModel() {
            Id = Usuario.Id,
            Email = Usuario.Email,
            Nombre = Usuario.Nombre,
            Apellido = Usuario.Apellido,
            AreaId = Usuario.AreaId,
            Alias = Usuario.Alias,
            //RolId = Usuario.RolId,
            //Para el llenado del comboBox de roles
            RolesList = ctx.Roles.ToList().Select(x => new SelectListItem()
            {
                Selected = UsuarioRol.Contains(x.Name),
                Text = x.Name,
                Value = x.Name
            })
        });
    }

RolesList returns the list of Roles and preselects the role of the user, until here everything works correctly, here's the post:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include= 
        "Id,Email,Alias,Nombre,Apellido,AreaId,RolId")]
        EditUsuarioViewModel editUser)
    {
       if(ModelState.IsValid)
        {
            var Usuario = UserManager.FindById(editUser.Id);

            if(Usuario == null)
            {
                return HttpNotFound();
            }

            Usuario.Email = editUser.Email;
            Usuario.UserName = editUser.Email;
            Usuario.AreaId = editUser.AreaId;
            Usuario.Nombre = editUser.Nombre;
            Usuario.Apellido = editUser.Apellido;
            Usuario.Alias = editUser.Alias;
            Usuario.RolId = editUser.RolId;

            //Verificamos si tiene un rol
            var UsuarioRol = UserManager.GetRoles(editUser.Id);

            //Si tiene rol pues lo quitamos
            if (UsuarioRol != null)
            {
                var quitar = UserManager.RemoveFromRoles(editUser.Id, UsuarioRol.ToArray());
                if(!quitar.Succeeded)
                {
                    ModelState.AddModelError("", quitar.Errors.First());
                    return View();
                }
            }

            //Agregamos el nuevo rol
            var result = UserManager.AddToRole(editUser.Id, editUser.RolId);
            if(!result.Succeeded)
            {
                ModelState.AddModelError("", result.Errors.First());
                return View();
            }

            return RedirectToAction("Index");
        }

        ModelState.AddModelError("", "No se pudo realizar los cambios");
        return View();
    }

the EditUsuarioViewModel class:

public class EditUsuarioViewModel
{
    public string Id { get; set; }

    [Required]
    [Display(Name = "Nombre del usuario")]
    public string Nombre { get; set; }

    [Required]
    [Display(Name = "Apellido del usuario")]
    public string Apellido { get; set; }

    [Required]
    [Display(Name = "Área")]
    public int AreaId { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Correo electrónico")]
    public string Email { get; set; }

    public string UserName { get; set; }

    [Required]
    [Display(Name = "Alias del Usuario")]
    public string Alias { get; set; }

    [Required]
    [Display(Name = "Rol")]
    public string RolId { get; set; }

    public string Foto { get; set; }

    public IEnumerable<SelectListItem> RolesList { get; set; }
}

In the view I create the DropDownList like this:

<div class="form-group">
            @Html.LabelFor(model => model.RolId, new { @class = "control-label col-md-2" })
            <div class=" col-md-10">
               <!-- AQUI ES DONDE MARCA EL ERROR -->
               @Html.DropDownListFor(model => model.RolId,Model.RolesList,"Seleccione un Rol")  
            </div>
        </div>

How can I be failing?

Greetings.

    
asked by Enecumene 19.04.2018 в 18:15
source

1 answer

0

The problem was that if an error occurred in the edition it returned the list to the view as null, the solution was to resend the list again every time the same view is called:

 [HttpPost]
 [ValidateAntiForgeryToken]
  public ActionResult Edit([Bind(Include= 
    "Id,Email,Alias,Nombre,Apellido,AreaId,RolId")]
    EditUsuarioViewModel editUser)
  {
   if(ModelState.IsValid)
    {
        var Usuario = UserManager.FindById(editUser.Id);

        if(Usuario == null)
        {
            return HttpNotFound();
        }

        Usuario.Email = editUser.Email;
        Usuario.UserName = editUser.Email;
        Usuario.AreaId = editUser.AreaId;
        Usuario.Nombre = editUser.Nombre;
        Usuario.Apellido = editUser.Apellido;
        Usuario.Alias = editUser.Alias;
        Usuario.RolId = editUser.RolId;

        //Verificamos si tiene un rol
        var UsuarioRol = UserManager.GetRoles(editUser.Id);

        //Si tiene rol pues lo quitamos
        if (UsuarioRol != null)
        {
            var quitar = UserManager.RemoveFromRoles(editUser.Id, UsuarioRol.ToArray());
            if(!quitar.Succeeded)
            {
                //Reenviar la lista de nuevo aquí
                ModelState.AddModelError("", quitar.Errors.First());
                return View();
            }
        }

        //Agregamos el nuevo rol
        var result = UserManager.AddToRole(editUser.Id, editUser.RolId);
        if(!result.Succeeded)
        {
            //Reenviar la lista de nuevo aquí
            ModelState.AddModelError("", result.Errors.First());
            return View();
        }

        return RedirectToAction("Index");
    }

    //Reenviar la lista de nuevo aquí
    ModelState.AddModelError("", "No se pudo realizar los cambios");
    return View();
}
    
answered by 19.04.2018 в 21:22