Search code examples
javascriptasp.net-mvcasp.net-mvc-5asp.net-identityclaims-based-identity

How to add a list of claims to user - AspNet MVC with MongoDB


@model Hub.MVC2.ViewModels.RegisterViewModel

@{
    ViewBag.Title = "Registrar";
}

<h2>Registrar</h2>


@using (Html.BeginForm("Register", "RegisterAdmin", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>RegisterViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CpfCnpj, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CpfCnpj, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CpfCnpj, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Telefone, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Telefone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Telefone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Claims, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="row">
                    <div class="col-md-4">
                        <select id="ddlClaims" class="form-control"></select>
                    </div>
                    <div class="col-md-1">
                        @*<button id="addPermissao" type="button" class="plus plus-left" title="Adicionar permissão" onclick="SetClaim($('#ddlClaims').val(), '@Model' )">&plus;</button>*@
                        <button id="addPermissao" type="button" class="plus plus-left" title="Adicionar permissão" >&plus;</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Role, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="row">
                    <div class="col-md-4">
                        <select id="ddlRoles" class="form-control" name="Role"></select>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-md-2" for="Claims">Lista Permissões</label>
            <div class="col-md-4">
                <table id="dtListaClaims" class="table"></table>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
            </div>
        </div>

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

@section Scripts {
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/comum/RegisterAdmin/Register.js" type="text/javascript"></script>
}

Hello!

I'm tying to create a Register user (Admin view) where I'll be able to set user's roles and claims but when I create the variable 'User' and try to set my list of claims into "Claims = {} " the code doesn't allow me to add the list.

I've tried to set by calling a method or using a foreach statement but it didn't work.

My controller code is:

 public class RegisterAdminController : Controller
{
    private readonly ClaimsBusiness _claims = new ClaimsBusiness();
    private readonly RolesBusiness _roles = new RolesBusiness();

    private static RegisterViewModel listaClaims = new RegisterViewModel();


    // GET: RegisterAdmin
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        // Esta linha tira a formatação da máscara criada via JQuery
        Regex pattern = new Regex("[() -.,]");
        if (ModelState.IsValid)
        {
            IdentityUserClaim claims;
            List<IdentityUserClaim> listaIdentityUserClaim = new List<IdentityUserClaim>();

            foreach (var indiceClaim in listaClaims.Claims)
            {
                claims = new IdentityUserClaim();

                claims.Id = indiceClaim.Id.ToString();
                claims.ClaimType = indiceClaim.ClaimType;
                claims.ClaimValue = indiceClaim.Ativo.ToString();
                listaIdentityUserClaim.Add(claims);
            }
            var user = new ApplicationUser
            {
                Nome = model.Nome,
                PhoneNumber = model.Telefone,
                CpfCnpj = model.CpfCnpj,
                UserName = model.Email,
                Email = model.Email,
                Roles =
                {
                    model.Role
                }, 
                Claims =
                {
                    listaIdentityUserClaim
                }
            };
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    [HttpGet]
    public string GetClaims()
    {
        try
        {
            StringBuilder retornoHTML = new StringBuilder();
            int i = 0;

            var listClaims = Mapper.Map<IEnumerable<DClaimsInfra>, IEnumerable<ClaimsViewModel>>(_claims.GetAll());
            retornoHTML.AppendLine("<option value='0'> --- Selecionar --- </option>");

            foreach (var claim in listClaims)
            {
                if (claim.Ativo)
                {
                    retornoHTML.AppendLine("<option value='" + claim.Id + "' id='" + claim.Id + "'>" + claim.ClaimType + "</option>");
                }
            }
            return retornoHTML.ToString();

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    [HttpGet]
    public string GetRoles()
    {
        try
        {
            StringBuilder retornoHTML = new StringBuilder();
            int i = 0;

            var listRoles = Mapper.Map<IEnumerable<DRolesInfra>, IEnumerable<RolesViewModel>>(_roles.GetAll());
            retornoHTML.AppendLine("<option value='0'> --- Selecionar --- </option>");

            foreach (var role in listRoles)
            {
                if (role.Ativo)
                {
                    retornoHTML.AppendLine("<option value='" + role.Id + "' id='" + role.Id + "'>" + role.Role + "</option>");
                }
            }
            return retornoHTML.ToString();

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    [HttpGet]
    public string SetClaimsList(string claimId, RegisterViewModel model)
    {
        try
        {
            StringBuilder retornoHTML = new StringBuilder();

            if (listaClaims.Claims == null)
                listaClaims.Claims = new List<ClaimsViewModel>();

            var getClaim = Mapper.Map<DClaimsInfra, ClaimsViewModel>(_claims.GetById(claimId));
            listaClaims.Claims.Add(getClaim);
            if (getClaim != null)
            {
                retornoHTML.AppendLine("<tr id='" + getClaim.Id + "'>");
                retornoHTML.AppendLine("    <td>" + getClaim.ClaimType + "</td>");
                retornoHTML.AppendLine("    <td><button id='removePermissao' type='button' class='minus minus-left' title='Remover permissão' onclick=\"RemoveClaim('" + claimId + "')\">&minus;</button></td>");
                retornoHTML.AppendLine("</tr>");

                return retornoHTML.ToString();
            }

            return "Erro ao procurar permissão!";

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    [HttpGet]
    public bool RemoveClaimsList(string claimId)
    {
        try
        {
            if (listaClaims.Claims == null)
                listaClaims.Claims = new List<ClaimsViewModel>();

            var getClaim = Mapper.Map<DClaimsInfra, ClaimsViewModel>(_claims.GetById(claimId));
            if (getClaim != null)
            {
                return listaClaims.Claims.Remove(listaClaims.Claims.Find(x => x.Id == getClaim.Id));
            }
            return false;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }
}

My Model:

 public class RegisterViewModel
{
    [Required]
    [StringLength(100, ErrorMessage = "O campo {0} precisa ter no mínimo {2} caracteres.", MinimumLength = 6)]
    [Display(Name = "Nome Completo")]
    public string Nome { get; set; }

    [Required]
    [Display(Name = "CNPJ / CPF")]
    public string CpfCnpj { get; set; }

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

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

    [Required]
    [StringLength(100, ErrorMessage = "O campo {0} precisa 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 = "As senhas não conferem.")]
    public string ConfirmPassword { get; set; }


    [Display(Name = "Permissões")]
    public List<ClaimsViewModel> Claims { get; set; }

    [Display(Name = "Grupo de usuário")]
    public string Role { get; set; }
}

My View:

@model Hub.MVC2.ViewModels.RegisterViewModel

@{
    ViewBag.Title = "Registrar";
}

<h2>Registrar</h2>


@using (Html.BeginForm("Register", "RegisterAdmin", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>RegisterViewModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Nome, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Nome, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CpfCnpj, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CpfCnpj, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CpfCnpj, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Telefone, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Telefone, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Telefone, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Claims, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="row">
                    <div class="col-md-4">
                        <select id="ddlClaims" class="form-control"></select>
                    </div>
                    <div class="col-md-1">
                        @*<button id="addPermissao" type="button" class="plus plus-left" title="Adicionar permissão" onclick="SetClaim($('#ddlClaims').val(), '@Model' )">&plus;</button>*@
                        <button id="addPermissao" type="button" class="plus plus-left" title="Adicionar permissão" >&plus;</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Role, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="row">
                    <div class="col-md-4">
                        <select id="ddlRoles" class="form-control" name="Role"></select>
                    </div>
                </div>
            </div>
        </div>

        <div class="form-group">
            <label class="control-label col-md-2" for="Claims">Lista Permissões</label>
            <div class="col-md-4">
                <table id="dtListaClaims" class="table"></table>
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
            </div>
        </div>

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

@section Scripts {
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    <script src="~/Scripts/comum/RegisterAdmin/Register.js" type="text/javascript"></script>
}

Can someone show me how to fix it?

Thanks.


Solution

  • SOLVED

    On page load I needed to call the controller via AJAX, get the list of claims and roles in data base, build the lists HTML code inside the controller and make JavaScript add the content into each list.

    I recognize that it isn't the bets practice to make "red code" into the controller but it worked well and I'm studying to make it better.

    Thanks.