0

我试图避免使用视图包来填充Html.DropDownListFor并且没有最好的运气。

我想提取特定 SQL 表上使用的所有状态代码并选择不同的值。然后,我想使用这些结果来填充视图上的下拉列表。

为了做到这一点,我创建了一个List<SelectListItem>作为我的视图模型的属性。在控制器中,我尝试使用 Linq 查询来加载List. 如果我单步执行代码,这似乎工作得很好(我可以看到List查询之后有 50 个条目),但是当页面加载时它会抛出一个NullReferenceException指向DropDownListFor.

查看模型

public class ZipCodeIndex
{
    public List<ZipCodeTerritory> zipCodeTerritory { get; set; }
    [DisplayName("Zip Code")]
    public string searchZip { get; set; }
    public List<SelectListItem> StateCodes { get; set; }
    [DisplayName("Effective on this date")]
    public string searchDate { get; set; }
    [DisplayName("State")]
    public string searchState { get; set; }
    [DisplayName("New Territory")]
    public string newTerritory { get; set; }
    [DisplayName("New Description")]
    public string newDescription { get; set; }
    [DisplayName("New Effective Date")]
    public string newEffectiveDate { get; set; }

    public ZipCodeIndex() 
    {
        zipCodeTerritory = new List<ZipCodeTerritory>();
    }
}

控制器

//Set state code drop down list
search.StateCodes = (from z in db.ZipCodeTerritory
                        select z.StateCode).Select(x => new SelectListItem
                        {
                            Text = x,
                            Value = x
                        }).Distinct().ToList();

看法

<div id="stateBox">
    @Html.LabelFor(model => model.searchState)
    @Html.DropDownListFor(model => model.searchState, Model.StateCodes, new { style = "width: 25px;", maxLength = 2 })
    <button type="submit" id="SearchButton">Search</button>
</div>
4

1 回答 1

0

这是因为return我的控制器中的声明而发生的。我设置了一个条件来确定这是否是初始页面加载,如果是,只需将用户发送回控制器。因此,return 语句很简单return View(),所以我没有将Model对象发送回视图。下面的代码解决了这个问题。(search是我的视图模型的一个实例)

        //Proceed with search
        try
        {
            //Set state code drop down list
            search.StateCodes = (from z in db.ZipCodeTerritory
                                    select z.StateCode).Select(x => new SelectListItem
                                    {
                                        Text = x,
                                        Value = x
                                    }).Distinct().ToList();

            //If search criteria is null page is loading for the first time so send blank view OR
            if (String.IsNullOrWhiteSpace(search.searchZip) &&
                String.IsNullOrWhiteSpace(search.searchDate) &&
                String.IsNullOrWhiteSpace(search.searchState))
            {
                return View(search);
            }
于 2013-10-07T20:59:33.980 回答