我需要帮助使用剃刀视图填充我的MVC应用程序中的状态下拉列表:
在我的模型中,我有一个sate属性:
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>
当我尝试访问我的视图时,我不断收到“对象引用未设置”错误
如何从此模型填充下拉列表?
答案 0 :(得分:0)
我认为你应该为你的模型添加一个属性
public string SelectedState { get; set; }
然后在视图中:
@Html.DropDownListFor(m => m.SelectedState, Model.State, new { @class="form-control" })
然后在提交时,您将获得模型的SelectedState
属性
答案 1 :(得分: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);
答案 2 :(得分:0)
你需要这样的房产:
public string State { get; set; }
Controller中的在ViewBag中设置你的词典
并在您看来:
@Html.DropDownListFor(m => m.State, new SelectList(ViewBag.States, "Key", "Value"))