ASP.NET MVC 5 RegisterView-如何实现下拉列表

问题描述

想在RegisterView上实现一个下拉列表,无法弄清楚该怎么做。我是asp.net mvc5的新手,并遵循以下代码优先方法。我已经有办公室用桌子了。我将列出所有代码。我认为(我不确定)我必须初始化列表,但不知道如何做以及在哪里放置

有一个示范Office.Cs

    public class Office
    {
        public byte Id { get; set; }
        public string Name { get; set; }
    }
}

身份模型

        public IEnumerable<Office> Office { get; set; }

        [Required]
        public byte OfficeId { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

AccountViewModel.cs

public class RegisterViewModel
    {
        public OfficeViewModel OfficeViewModel { get; set; }
                     
        [Required]
        [Display(Name = "Office")]
        public byte OfficeId { get; set; }

AccountController.cs

            if (ModelState.IsValid)
            {
                
                
                var user = new ApplicationUser { UserName = model.Email,Email = model.Email,OfficeId= model.OfficeId};
                var result = await UserManager.CreateAsync(user,model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user,isPersistent:false,rememberBrowser:false);
                    
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this 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,"Confirm your account","Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    
                    return RedirectToAction("Index","Home");
                }
                AddErrors(result);

RegisterView.cshtml

        <div class="form-group">
            @Html.LabelFor(m => m.OfficeId)
            @Html.DropDownListFor(m => m.OfficeId,new SelectList(Model.Office,"Id","Name"),"Select",new { @class = "form-control" })
        </div>

解决方法

在您的控制器中

List<SelectListItem> li = new List<SelectListItem>();
// add you data to the list
var query = from of in your_context.Office
            select new SelectListItem()
            {
                  Text = of.Name,Value = of.Id
            };
li = query.ToList();
ViewBag.Office = li;

在视图中

<div class="col-md-10">
   @Html.DropDownList("Office",ViewBag.Office as List<SelectListItem>,new { @class = "form-control" })
</div>
,

您需要在SelectList类型字段中填充数据,该字段应在ViewModel类中声明。 SelectList类型集合的此字段将在View中用于与下拉列表绑定。

在我对另一篇文章的回答中对此进行了解释: MVC C# Dropdown list Showing System.Web.SelectListItem on the model and can not blind to controller

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...