如何向用户添加声明列表 - 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>
}

你好!

我想创建一个注册用户(管理员视图),我可以在其中设置用户的角色和声明,但是当我创建变量“用户”并尝试将我的声明列表设置为“声明 = {}”时代码不允许我添加列表。

我尝试通过调用方法或使用 foreach 语句进行设置,但没有奏效。

我的控制器代码是:

 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;
        }
    }
}

我的型号:

 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; }
}

我的看法:

@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>
}

有人可以告诉我如何修复它吗?

谢谢。

格伦马特乌斯

解决了

在页面加载时,我需要通过 AJAX 调用控制器,获取数据库中的声明和角色列表,在控制器内构建列表 HTML 代码并使 JavaScript 将内容添加到每个列表中。

我认识到将“红色代码”放入控制器并不是一种赌注做法,但它运行良好,我正在研究使其变得更好。

谢谢。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

MVC5 aspnet身份如何禁用声明

来自分类Dev

ASP MVC 5(Microsoft.AspNet.Identity)用户管理包

来自分类Dev

如何在ASPNET Core MVC中处理JWT

来自分类Dev

如何使用aspnet核心SignalR向用户发送私人消息?

来自分类Dev

无法在MVC5 Microsoft.AspNet.Identity.EntityFramework.IdentityRole中添加新角色?

来自分类Dev

如何在ASP MVC 5(Microsoft.AspNet.Identity)中存根User.Identity.GetUserId()

来自分类Dev

如何调试在Azure中部署的ASPNET Core MVC应用程序

来自分类Dev

当我使用MVC3时如何使用DotNetOpenAuth.AspNet提供社交登录

来自分类Dev

Microsoft.AspNet.Identity MVC 如何配置系统自动使用令牌但无密码登录

来自分类Dev

如何使用AspNet.Identity使用Asp.Net MVC5 RTM位登录/认证用户?

来自分类Dev

ASPNET MVC LabelFor或EditorFor使用for循环

来自分类Dev

MVC5和ASPNET Identity 2.0

来自分类Dev

在ASPNET MVC SinglePageApplication中缓存数据

来自分类Dev

模型之外的ASPNet MVC上的业务逻辑

来自分类Dev

ASPNET MVC-模型中包含什么?

来自分类Dev

ASPNET Core MVC - 获取 url 的表单

来自分类Dev

AspNet MVC通过用户名为任何用户(不是当前用户)获取用户或身份对象

来自分类Dev

ASPNet MVC-在控制器方法中,返回字符串列表或重定向到其他页面

来自分类Dev

如何在AspNet.Identity版本3 / ASP.Net MVC6 / VNext中检索FacebookAccessToken?

来自分类Dev

如何在aspnet core mvc中使用swagger为表单主体提供多种数据类型?

来自分类Dev

如何在 ASPNET BOILERPLATE MVC5 中将另一个页面设置为默认页面?

来自分类Dev

在aspnet core mvc中删除数据后如何使用jquery延迟3000秒重定向页面

来自分类Dev

以ASP.NET MVC结构向用户添加公司

来自分类Dev

我的模型如何识别AspNet

来自分类Dev

Aspnet MVC 4验证十进制数字

来自分类Dev

视图中的ASPNET MVC格式化字符串

来自分类Dev

Aspnet MVC 4验证十进制数字

来自分类Dev

代码优先MVC-AspNet表在哪里实现?

来自分类Dev

带有EF-SUM和GROUP BY的ASPNET MVC

Related 相关文章

  1. 1

    MVC5 aspnet身份如何禁用声明

  2. 2

    ASP MVC 5(Microsoft.AspNet.Identity)用户管理包

  3. 3

    如何在ASPNET Core MVC中处理JWT

  4. 4

    如何使用aspnet核心SignalR向用户发送私人消息?

  5. 5

    无法在MVC5 Microsoft.AspNet.Identity.EntityFramework.IdentityRole中添加新角色?

  6. 6

    如何在ASP MVC 5(Microsoft.AspNet.Identity)中存根User.Identity.GetUserId()

  7. 7

    如何调试在Azure中部署的ASPNET Core MVC应用程序

  8. 8

    当我使用MVC3时如何使用DotNetOpenAuth.AspNet提供社交登录

  9. 9

    Microsoft.AspNet.Identity MVC 如何配置系统自动使用令牌但无密码登录

  10. 10

    如何使用AspNet.Identity使用Asp.Net MVC5 RTM位登录/认证用户?

  11. 11

    ASPNET MVC LabelFor或EditorFor使用for循环

  12. 12

    MVC5和ASPNET Identity 2.0

  13. 13

    在ASPNET MVC SinglePageApplication中缓存数据

  14. 14

    模型之外的ASPNet MVC上的业务逻辑

  15. 15

    ASPNET MVC-模型中包含什么?

  16. 16

    ASPNET Core MVC - 获取 url 的表单

  17. 17

    AspNet MVC通过用户名为任何用户(不是当前用户)获取用户或身份对象

  18. 18

    ASPNet MVC-在控制器方法中,返回字符串列表或重定向到其他页面

  19. 19

    如何在AspNet.Identity版本3 / ASP.Net MVC6 / VNext中检索FacebookAccessToken?

  20. 20

    如何在aspnet core mvc中使用swagger为表单主体提供多种数据类型?

  21. 21

    如何在 ASPNET BOILERPLATE MVC5 中将另一个页面设置为默认页面?

  22. 22

    在aspnet core mvc中删除数据后如何使用jquery延迟3000秒重定向页面

  23. 23

    以ASP.NET MVC结构向用户添加公司

  24. 24

    我的模型如何识别AspNet

  25. 25

    Aspnet MVC 4验证十进制数字

  26. 26

    视图中的ASPNET MVC格式化字符串

  27. 27

    Aspnet MVC 4验证十进制数字

  28. 28

    代码优先MVC-AspNet表在哪里实现?

  29. 29

    带有EF-SUM和GROUP BY的ASPNET MVC

热门标签

归档