The Viewdata item that has the 'Name' key is of the 'System.String' type, but must be of the 'Ienumerable<Selectlistitem> type

Asked

Viewed 72 times

1

Speak, guys, I’m new in the area of ASP.NET and studying Identity I came across a typo error when performing a new user registration. The project was done with the authenticity of the VS. I did the part of Roles, which are working very well, the problem is when you register a new user with the already registered role.

The error is generated in the View Register @Html.Dropdownlist("Name") line when trying to register the new user.

The Viewdata item that has the 'Name' key is of the 'System.String' type, but needs to be of the 'Ienumerable' type'.

My Registerviewmodel inside the Accountviewmodel:

public class RegisterViewModel
{
    [Display(Name = "Nome")]
    public string Name { get; set; }

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

    [Required]
    [StringLength(100, ErrorMessage = "O/A {0} deve ter no mínimo {2} caracteres.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Senha")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirmar Senha")]
    [Compare("Password", ErrorMessage = "A senha e a senha de confirmação não correspondem.")]
    public string ConfirmPassword { get; set; }
}

My Controller (GET and POST) inside the Accountcontroller:

    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //Atribui o Peril ao usuário
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                //fim da atribuição

                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                
                // Para obter mais informações sobre como habilitar a confirmação da conta e redefinição de senha, visite https://go.microsoft.com/fwlink/?LinkID=320771
                // Enviar um email com este link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirmar sua conta", "Confirme sua conta clicando <a href=\"" + callbackUrl + "\">aqui</a>");

                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // Se chegamos até aqui e houver alguma falha, exiba novamente o formulário
        return View(model);
    }

And my View Account/Register:

   @model CadastroUsuariosProdutos.Models.RegisterViewModel

    @{
       ViewBag.Title = "Registre-se";
     }

   <h2>@ViewBag.Title.</h2>

   @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
  {
   @Html.AntiForgeryToken()
   <h4>Crie uma nova conta.</h4>
   <hr />
   @Html.ValidationSummary("", new { @class = "text-danger" 
  })
   <div class="form-group">
    @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
    </div>
</div>

<!-- Selecionar o Tipo de Perfil para o usuário -->
<div class="form-group">
    @Html.Label("Selecione o Tipo de Perfil do Usuário", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("Name")
    </div>
</div>
<!-- Fim da seleção do tipo de usuário -->

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" class="btn btn-default" value="Registrar-se" />
    </div>
</div>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

1 answer

0

You are passing the list of Names, which are your roles through the ViewBag.Name

// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
    ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
    return View();
}

But in your View you are trying to mount the Dropdown from the property Name of his RegisterViewModel

<!-- Selecionar o Tipo de Perfil para o usuário -->
<div class="form-group">
    @Html.Label("Selecione o Tipo de Perfil do Usuário", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("Name")
    </div>
</div>

For it to work properly you need to popular this dropdown by Viewbag

@Html.DropDownList("Name", ViewBag.Name)
  • Hello Leandro. So this line with Viewbag.Name does not compile. Actually the dropdown is being populated correctly, but it is when a new user will register that this happens. The Get is working.I will put the Registerviewmodel.

  • public class Registerviewmodel { [Display(Name = "Name")] public string Name { get; set; } [Required] [Emailaddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [Stringlength(100, Errormessage = "O/A {0} must have at least {2} characters." , Minimumlength = 6)] [Datatype(Datatype.Password)] [Display(Name = "Password")]

  • It had an extra parenthesis, you tried to remove?

  • Yes, I had noticed. It did not compile.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.