【问题标题】:Add a dropdown for a field not in the model (asp.net mvc)为不在模型中的字段添加下拉列表(asp.net mvc)
【发布时间】:2015-10-13 00:48:31
【问题描述】:

我正在使用 Active Directory 身份验证库来创建用户并列出它们。 我有一个视图和控制器操作来执行此操作。

但是请查看视图的模型,它是来自 Azure Active Directory 的 API 的用户实体

@model Microsoft.Azure.ActiveDirectory.GraphClient.User
@{
    ViewBag.Title = "Create";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
}

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-sm-4">
        <h2>Create</h2>
        <ol class="breadcrumb">
            <li>
                @Html.ActionLink("List", "Index")
            </li>
            <li class="active">
                <strong>Create</strong>
            </li>
        </ol>
    </div>
    <div class="col-sm-8">
        <div class="title-action">
            @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-primary"})
        </div>
    </div>
</div>


<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>Crear Usuario</h5>
                </div>
                <div class="ibox-content">

                    @using (Html.BeginForm())
                    {
                        @Html.ValidationSummary(true)

                        <fieldset>
                            <legend>User</legend>
                            <div class="editor-label">
                                @Html.LabelFor(model => model.UserPrincipalName)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.UserPrincipalName)
                                @Html.ValidationMessageFor(model => model.UserPrincipalName)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.AccountEnabled)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.AccountEnabled)
                                @Html.ValidationMessageFor(model => model.AccountEnabled)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.PasswordProfile.Password)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.PasswordProfile.Password)
                                @Html.ValidationMessageFor(model => model.PasswordProfile.Password)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.MailNickname)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.MailNickname)
                                @Html.ValidationMessageFor(model => model.MailNickname)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.DisplayName)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.DisplayName)
                                @Html.ValidationMessageFor(model => model.DisplayName)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.GivenName)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.GivenName)
                                @Html.ValidationMessageFor(model => model.GivenName)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.Surname)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.Surname)
                                @Html.ValidationMessageFor(model => model.Surname)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.JobTitle)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(model => model.JobTitle)
                                @Html.ValidationMessageFor(model => model.JobTitle)
                            </div>

                            <div class="editor-label">
                                @Html.LabelFor(model => model.Department)
                            </div>

                            <div class="editor-field">
                                @Html.EditorFor(model => model.Department)
                                @Html.ValidationMessageFor(model => model.Department)
                            </div>

                            <div class="editor-label">
                                @Html.Label("Empresa")
                            </div>
                            @{
                                List<SelectListItem> listItems = new List<SelectListItem>();
                                listItems.Add(new SelectListItem
                                {
                                    Text = "Company1",
                                    Value = "Company1"
                                });
                                listItems.Add(new SelectListItem
                                {
                                    Text = "Company2",
                                    Value = "Company2",
                                    Selected = true
                                });
                                listItems.Add(new SelectListItem
                                {
                                    Text = "Company3",
                                    Value = "Company3"
                                });
                            }
                            <div class="editor-field">
                                @Html.DropDownListFor(model => model.Department)
                            </div>

                            <p>
                                <input type="submit" value="Create" />
                            </p>
                        </fieldset>
                    }


                </div>
            </div>
        </div>
    </div>
 </div>

在预置 AD 中的 Azure Active Directory 中,您可以添加自定义属性,这些自定义属性称为 azure Active Directory 架构扩展。它们在这里得到了很好的解释:http://justazure.com/azure-active-directory-part-6-schema-extensions/

但这不是我关心的问题。

我的 Active Directory 已经有一个名为 company 的新扩展属性。 我现在设置该扩展属性值的代码,检查此控制器操作,待完成的行

 public async Task<ActionResult> Create(
            [Bind(
                Include =
                    "UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department"
                )] Microsoft.Azure.ActiveDirectory.GraphClient.User user)
        {
            ActiveDirectoryClient client = null;
            try
            {
                client = AuthenticationHelper.GetActiveDirectoryClient();
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext()
                        .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return View();
            }

            try
            {
                await client.Users.AddUserAsync(user);

                //TO BE FINISHED
                user.SetExtendedProperty("Compania", "");
                await user.UpdateAsync();
                Task.WaitAll();

                // Save the extended property value to Azure AD.
                user.GetContext().SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return View();
            }
        }

问题是:

  1. DropDownListFor 需要模型中的属性,但在 User 类中没有属性,所以我该如何创建下拉列表?,在我看来,你可以看到有示例数据,我会处理稍后用来自数据源的真实数据修复它。

  2. 修复该问题后,如何获取控制器中选定下拉列表的值?

【问题讨论】:

  • 您为什么不使用包含您想要的属性的视图模型?但是一个技巧是使用@HtmlDropDownList("someProperty", yourSelectList),然后在 POST 方法中添加一个附加参数 - 例如int SomeProperty

标签: c# asp.net asp.net-mvc razor


【解决方案1】:

您始终可以将键值对列表属性添加到您的视图模型。当您的用户向您的 AD 实体添加扩展属性时,您可以扩展该列表。当您传递到您的视图时,您的列表可以作为一个空集合开始。然后在您的视图中,您遍历集合中的项目以在列表类型显示中显示每个键值对。

您的控制器可以有一个方法来提供键值对条目的部分视图(即,具有两个输入的部分视图:一个用于属性名称,一个用于值),因此当用户单击按钮时您的视图添加一个新的扩展属性,您调用该控制器方法为您提供输入字段的呈现。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
相关资源
最近更新 更多