很难让选定的值粘在ASP.NET MVC页面上。
public partial class AdjustedCost
{
public SelectList BrandList { get; set; }
public string Brand { get; set; }
}
BrandList已在控制器中设置:
private static SelectList BrandList = new SelectList( new[] { "Brand1","Brand2","Brand3" } );
public ActionResult EditByTextbox(String textBoxEdit)
{
...
AjustedCost xadjcost = db.xAdjCost.First(e => e.InvtId == textBoxEdit);
...
xadjcost.BrandList = BrandList;
return View( "Edit", xadjcost);
}
在编辑视图中:
@Html.DropDownListFor(model => model.Brand, Model.BrandList )
这是对的吗?下拉部分正在运行,但所选值只是返回列表的顶部,而不是实际当前设置的值。
答案 0 :(得分:1)
您需要将selectedValue传入SelectList()的构造函数,而不是使用该静态变量,该变量没有来自数据库的当前值的上下文。
因此,我会创建一种方法,在您需要选择的值的上下文中为您提供选择列表,即
private SelectList BrandList(string selectedValue)
{
SelectList selectList = null;
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "Brand1", Value = "Brand1" });
selectListItems.Add(new SelectListItem { Text = "Brand2", Value = "Brand2" });
selectListItems.Add(new SelectListItem { Text = "Brand3", Value = "Brand3" });
selectList = new SelectList(selectListItems, "Value", "Text", selectedValue);
}
catch (Exception exception)
{
exception.Log(); // or whatever you do with your exceptions
}
return selectList;
}
因此,在你的行动结果中,这个:
xadjcost.BrandList = BrandList;
变为:
xadjcost.BrandList = BrandList(whateverTheBrandValueFromYourDbIs);