generate dropdownlist from a table in database

你离开我真会死。 提交于 2019-12-06 20:16:39

You'd better have a view model specifically designed for this view. Think of what information you need in the view and define your view model:

public class RegisterViewModel
{
    public string Email { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string SelectedRole { get; set; }
    public IEnumerable<SelectListItem> Roles { get; set; }
}

As you can see from this view model, in order to have a dropdown list you need 2 properties: one scalar property that will hold the selected value and one collection property to hold the list of available values.

and then:

public ActionResult Register()
{
    string [] roles = Roles.GetAllRoles();
    var model = new RegisterViewModel();
    model.Roles = roles.Select(r => new SelectListItem 
    {
        Value = r,
        Text = r,
    });
    return View(model);
}

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    // the model.SelectedRole will contain the selected value from the dropdown
    // here you could perform the necessary operations in order to create your user
    // based on the information stored in the view model that is passed

    // NOTE: the model.Roles property will always be null because in HTML,
    // a <select> element is only sending the selected value and not the entire list.
    // So if you intend to redisplay the same view here instead of redirecting
    // makes sure you populate this Roles collection property the same way we did 
    // in the GET action

    return Content("Thanks for registering");
}

and finally the corresponding view:

@model RegisterViewModel
@{
    ViewBag.Title = "Register";
    Layout = "~/Views/shared/_BootstrapLayout.empty.cshtml";
}

@section Styles{
    <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
}
<div class ="form-signin">
    @using (Html.BeginForm("Login", "Account"))
    {
        @Html.ValidationSummary(true)
        <h2 class="form-signin-heading"> Register </h2>
        <div class ="input-block-level">
            @Html.TextBoxFor(model => model.Email, new { placeholder = "Email" })
        </div>
        <div class ="input-block-level">
            @Html.TextBoxFor(model => model.UserName, new { placeholder = "UserName" })
        </div>
        <div class ="input-block-level">
            @Html.PasswordFor(model => model.Password, new { placeholder = "Password" })
        </div>
        <div class ="input-block-level">
            @Html.DropdownlistFor(model => model.SelectedRole, Model.Roles)
        </div>

        <button class="btn btn-large btn-primary" type="submit">Sign In</button>
    }
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!