0

很难将所选值粘贴在 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 )

这个对吗?下拉部分正在工作,但所选值仅返回列表顶部,而不是当前设置的实际值。

4

1 回答 1

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);
于 2013-05-23T16:02:47.243 回答