在MVC视图中填充下拉列表 [英] Populate a Dropdown List in MVC View

查看:118
本文介绍了在MVC视图中填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC框架的新手,无法弄清楚如何填充与数据库绑定的下拉列表.请使用以下代码在视图部分中帮助我,因为我想在下拉列表中显示帐户名称.

型号:-

 [Table("account")]
public class Accounts
{
    [Key]
    public int acc_id { get; set; }
    public string acc_name { get; set; }
    // public SelectList AccountList { get; set; }  
}
 

AccountsContext

 public class AccountsContext:DbContext
{
    public DbSet<Accounts> Account { get; set; }
    // public SelectList Accounts { get;set;}
}
 

控制器:-

 public ActionResult Group()
{
    Accounts ak = new Accounts();
    AccountsContext accountscontext = new AccountsContext();
    List<Accounts> account = accountscontext.Account.ToList();
    return View(account);
}
 

解决方案

您正在将帐户列表作为模型发送到视图.没关系.但是,您将如何获得用户选择的价值呢?为此,您应该在服务器端将一个属性绑定到客户端上的选定项.

我建议使用ViewModel,该模型将具有作为SelectListItem集合的帐户列表(将在控制器中填充)和所选项目的另一个属性,然后将帐户列表不直接传递给视图应该通过新的viewModel并进行相应的绑定.

ViewModel

public class AccountsViewModel
{
    public int SelectedAccountId { get; set; }
    public IEnumerable<SelectListItem> Accounts{ get; set; }
}

查看

@model AccountsViewModel
@Html.DropDownListFor(m => m.SelectedAccountId , Model.Accounts)

I am new to MVC framework and cant figure out how to populate a dropdown list which binds with the database.Please help me in the view part as I want to show the Account Name in dropdown list using the following code.

Model:-

[Table("account")]
public class Accounts
{
    [Key]
    public int acc_id { get; set; }
    public string acc_name { get; set; }
    // public SelectList AccountList { get; set; }  
}

AccountsContext

public class AccountsContext:DbContext
{
    public DbSet<Accounts> Account { get; set; }
    // public SelectList Accounts { get;set;}
}

Controller:-

public ActionResult Group()
{
    Accounts ak = new Accounts();
    AccountsContext accountscontext = new AccountsContext();
    List<Accounts> account = accountscontext.Account.ToList();
    return View(account);
}

解决方案

You are sending the list of accounts as model to your view. That's fine. But how are you going to get the value that the user would select? For that you should have a property at you server side binded to the selected item at client-side.

I would suggest using a ViewModel which would have the list of accounts as collection of SelectListItem (which would be populated in the controller) and another property for the selected item and then instead of passing the list of accounts directly to your view you should pass the new viewModel and bind accordingly.

ViewModel

public class AccountsViewModel
{
    public int SelectedAccountId { get; set; }
    public IEnumerable<SelectListItem> Accounts{ get; set; }
}

View

@model AccountsViewModel
@Html.DropDownListFor(m => m.SelectedAccountId , Model.Accounts)

这篇关于在MVC视图中填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆