设置DropDownListFor默认文本MVC

时间:2017-03-31 22:38:30

标签: asp.net-mvc

我是MVC的新手,我正在尝试做一些应该很容易的事情,但这是在逃避我。我在局部视图中使用DropDownListFor来显示产品名称列表。那部分工作正常。我遇到的问题是设置DropDownListFor的初始值以显示"选择一个"。我正在使用的代码如下:

@Html.DropDownListFor(model => model.ProductId, new SelectList(ViewBag.ProductData, "ProductId", "Name"), "---Select one---", new {  htmlAttributes = new { @id = "ProductName" } });

设置ViewBag的控制器如下:

public ActionResult AddProduct(int quoteId, int quoteDetailId)
        {
            var items = db.Products.ToList();
            ViewBag.ProductData = items;

            ViewData["QuoteId"] = quoteId;
            ViewData["QuoteDetailId"] = quoteDetailId;
            return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 1, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
        }

一旦我点击DropDownListFor上的下拉箭头,"选择一个"出现在列表的顶部。但是当首次显示DropDownListFor时,第一个产品名称会出现在框中,而不是"选择一个"。我怎样才能解决这个问题?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

不要在模型中为id属性指定值:

public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
    var items = db.Products.ToList();
    ViewBag.ProductData = items;

    return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 0, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}