从数据库绑定DropDownList [英] Binding DropDownList from Database

查看:69
本文介绍了从数据库绑定DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个视图,该视图将基于来自两个下拉列表的选择显示表格数据,第一个选择部门的信息已从数据库中填充.第二个是年"的静态下拉列表.我还没有.有类似问题的答案,但我已经看过它们并尝试了所有方法.我已经到了为下拉列表创建标记的视图中出现空异常的地步.

I'm building a view which will display tabular data based on selections from two dropdownlists, the first which selects departments is populated from the database. The second is a static dropdownlist for "Year" which I haven't got to yet. There are answers to similar questions, but I've looked at them and tried everything. I've got to the point where I'm getting a null exception in the view where I created the markup for the dropdownlist.

查看:

部门返回为空.我是MVC的新手,可以通过在线

Departments is coming back as null. I'm new to MVC and pieced this together from online examples. I'm guessing my model is wrong.

@model IEnumerable<BudgetDemo.Models.BudgetsActualsViewModel>

@foreach (var item in Model)
{
    @Html.DropDownListFor(m => item.Departments, 
        new SelectList(item.Departments.Select(x => x.Text)))
}

ViewModel:

public class BudgetsActualsViewModel
{
    [Display(Name = "Cost Center/Department")]
    [Required(ErrorMessage = "Cost Center/Department is required.")]
    [StringLength(62)]
    public string SelectedDepartment { get; set; }
    public IEnumerable<SelectListItem> Departments { get; set; }
}

控制器:

public ActionResult GetBudgetsActuals()   
{
    repo = new BudgetDemoRepository();
    ModelState.Clear();
    return View(repo.GetBudgetsActuals());
}

存储库类别:

public List<BudgetsActualsViewModel> GetBudgetsActuals()  
{
    ...
    List<BudgetsActualsViewModel> budgetsActualsList = new List<BudgetsActualsViewModel>();
    // Query returning correct data from DB here

    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        budgetsActualsList.Add(
            new BudgetsActualsViewModel
             {
                 SelectedDepartment = ds.Tables[0].Rows[i]["Department"].ToString()
             }
        );
    }
    return budgetsActualsList;
}

推荐答案

因此,您要将值保存在 SelectedDepartment 属性中,并访问 Departments 列表.从来没有初始化过,所以显然是 null .

So, You are saving the values in SelectedDepartment property and accessing the Departments list. Which is never initialized so it would obviously be null.

像这样修改您的 GetBudgetsActuals 方法:

public BudgetsActualsViewModel GetBudgetsActuals()  
{
    ...
    BudgetsActualsViewModel budgetsActuals = new BudgetsActualsViewModel(){ Departments = new List<SelectListItem>() };
    // Query returning correct data from DB here

    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
        budgetsActuals.Departments
                      .Add(new SelectListItem 
                          { 
                              Text = ds.Tables[0].Rows[i]["Department"].ToString(), 
                              Value = ds.Tables[0].Rows[i]["YourRowId"].ToString() 
                          });
    }
    return budgetsActuals;
}

这是您的视图"外观:

@model BudgetDemo.Models.BudgetsActualsViewModel
@Html.DropDownListFor(m => m.SelectedDepartment, Model.Departments))

注意,我们摆脱了 foreach 循环.我们只需要调用 DropDownListFor()方法一次.

Notice, we got rid of the foreach loop. We need DropDownListFor() method to be called only once.

更新

public class BudgetsActualsViewModel
{
    [Display(Name = "Cost Center/Department")]
    [Required(ErrorMessage = "Cost Center/Department is required.")]
    [StringLength(62)]
    public string SelectedDepartment { get; set; }
    public List<SelectListItem> Departments { get; set; } // Modify it to list instead IEnumerable.
}

这篇关于从数据库绑定DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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