DropDownList设置MVC5中的选定项

时间:2014-08-17 20:51:21

标签: asp.net-mvc

如何设置DrowDownList的默认值?

我有这样的事情:

@Html.DropDownListFor(model => model.BusinessID, (SelectList)ViewBag.Businesses, new { @class = "form-control" })

修改

    // GET: Reviews/Create
    public ActionResult Create()
    {
        ViewBag.Businesses = new SelectList(db.Businesses, "BusinessID", "BusinessName");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ReviewID,ReviewText,Rating,BusinessID")] Review review, int id)
    {
        if (ModelState.IsValid)
        {
            db.Reviews.Add(review);
            db.SaveChanges();
            return RedirectToAction("Details", "Businesses", new { id = review.BusinessID });
        }

        review.BusinessID = id;
        ViewBag.Businesses = new SelectList(db.Businesses, "BusinessID", "BusinessName", review.BusinessID);
        return View(review);
    }

我如何称呼它:

@Html.ActionLink("Write a review", "Create", "Reviews", new { id = Model.BusinessID }, null)

关键是每个我的BusinessID都有一个值,我称它们就像这样/ Reviews / Create / 15,所以在这种情况下BusinessID是15.当页面加载时,我想要的项目是默认情况下要选择的BusinessID 15。但每当我加载页面时,它总是选择具有最低BusinessID的那个。

更新

将GET操作更改为此解决了问题:

        public ActionResult Create(int? id)
        {
            ViewBag.Businesses = new SelectList(db.Businesses, "BusinessID", "BusinessName", id);
            return View();
        }

2 个答案:

答案 0 :(得分:3)

你真的应该使用强类型版本,它使这更容易,并且更不容易出错。

@Html.DropDownListFor(x => x.BusinessID, Model.Businesses, new { @class="form-control" })

这里。 Model.Businesses是一个IEnuerable(可以是List,Collection,array等)。

或者您可以使用ViewBag,如​​下所示:

@Html.DropDownListFor(x => x.BusinessID, ViewBag.Businesses, new { @class="form-control" })

现在,我不清楚你的“默认值”是什么意思。您是否要将值设置为数据库中的值?在这种情况下,您只需使用您希望将其设置为的值填充您的model.BusinessID(确保它是值,而不是文本),它将在呈现页面时自动选择它。

如果您的意思是想要“选择商家......”,那么您将使用“选项”重载:

@Html.DropDownListFor(x => x.BusinessID, ViewBag.Businesses, "Select a Business...", new {@class="form-control" })

注意:不要将SelectListItems(或您的SelectList)列表命名为与Selected item属性相同,即..不要这样做:

@Html.DropDownListFor(x => x.BusinessID, ViewBag.BusinessID, "Select a Business...", new {@class="form-control" })

答案 1 :(得分:1)

将模型传递给视图时,请设置模型的BusinessID属性。 使用以下代码:

//Assuming you bind the model to View using Create Action
 public ActionResult Create()
{
    ViewBag.Businesses = new SelectList(db.Businesses, "BusinessID", "BusinessName");
    var reviewModel = new Review();
    reviewModel.BusinessID = 15;
    return View(reviewModel);
}

主要部分是在将模型绑定到视图时设置“BusinessID”属性的值。