0

我需要帮助使用剃刀视图填充 MVC 应用程序中的状态下拉列表:

在我的模型中,我有一个状态属性:

 public SelectList State
    {
        get { return new SelectList(StateDictionary, "Value", "Key"); }
    }

这是状态字典的缩短版本

public static readonly IDictionary<string, string> StateDictionary = new 

    Dictionary<string, string> {
            {"ALABAMA", "AL"},
            {"ALASKA", "AK"},
            {"AMERICAN SAMOA", "AS"},
            {"ARIZONA ", "AZ"},
            {"ARKANSAS", "AR"},
            {"CALIFORNIA ", "CA"},
            {"COLORADO ", "CO"},
            {"CONNECTICUT", "CT"},
            {"DELAWARE", "DE"},
            {"DISTRICT OF COLUMBIA", "DC"},
            {"FEDERATED STATES OF MICRONESIA", "FM"},
            {"FLORIDA", "FL"},
            {"GEORGIA", "GA"},
};

在我的 Razor 视图中,我有:

<div class="form-group">
                        @Html.LabelFor(m => m.State,new{@class="col-lg-2 control-label"})
                        @Html.DropDownListFor(m => m.State,Model.State,new {@class="form-control" })

                    </div>

当我尝试访问我的视图时,我不断收到“未设置对象引用”错误

如何从此模型填充下拉列表?

4

3 回答 3

0

我认为你应该在你的模型中添加一个属性

public string SelectedState { get; set; }

然后在视图中:

@Html.DropDownListFor(m => m.SelectedState, Model.State, new { @class="form-control" })

然后在提交时,您将获得模型SelectedState属性上的选定状态值

于 2013-10-13T18:31:34.513 回答
0

尝试以下操作:

你的模型

public class YourModel
{
    public string SelectedValue { get; set; }
    public SelectList Values { get; set; }
}

你的控制器

public ActionResult YourMethod()
{
    var dictionary = new Dictionary<string, string>
    {
        {"ALABAMA", "AL"},
        {"ALASKA", "AK"},
        {"AMERICAN SAMOA", "AS"},
        {"ARIZONA ", "AZ"},
        {"ARKANSAS", "AR"},
        {"CALIFORNIA ", "CA"},
        {"COLORADO ", "CO"},
        {"CONNECTICUT", "CT"},
        {"DELAWARE", "DE"},
        {"DISTRICT OF COLUMBIA", "DC"},
        {"FEDERATED STATES OF MICRONESIA", "FM"},
        {"FLORIDA", "FL"},
        {"GEORGIA", "GA"},
    };

    var model = new YourModel
    {
        // Choose one of the below options for displaying either the long or short name in the dropdown
        //Values = new SelectList(dictionary, "value", "key")
        Values = new SelectList(dictionary, "key", "value")
    };

    return View(model);
}

你的看法

@model YourModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values);
于 2013-10-13T18:44:43.590 回答
0

你需要这样的属性:

public string State { get; set; }

在控制器中设置你的字典在 ViewBag

在您看来:

@Html.DropDownListFor(m => m.State, new SelectList(ViewBag.States, "Key", "Value"))
于 2013-10-13T18:44:59.610 回答