So I can easily set the select value of my drop-down list in my Edit View if I don't using the htmlAttributes overloaded method. So the below works:
Edit View razor
@Html.DropDownList("CategoriesId")
Controller
public ActionResult Edit(int? id)
{
if (id==null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Budget budget = db.BudgetData.Find(id);
if (budget == null)
{
return HttpNotFound();
}
ViewBag.CategoriesId = new SelectList(db.Categories, "Id", "Description", budget.CategoriesId);
return View(budget);
}
No problem with the above but I want to be able to set the class using the htmlAttributes without using jQuery or some similar way.
As soon as I change my Edit View to the below it now has a nice bootstrap class but the selected value for that record has now been lost and it it always just shows the first record. I'm sure its something simple but I'm new to MVC :)
New htmlAttribute Razor
@Html.DropDownList("CategoriesId", (IEnumerable<SelectListItem>)ViewBag.CategoriesId, new { @class="form-control"})
I have also tried the below controller code but to no avail.
ViewBag.CategoriesId = db.Categories.AsEnumerable().Select(s => new SelectListItem { Text = s.Description, Value = s.Id.ToString(), Selected = budget.CategoriesId == s.Id });
Thanx for the helps guys.
--EDIT FOR ANSWER INFO--
After finding out that my DDL with ViewBag.CategoriesId can't be the same as my model etc causing the above the question. I changed my ViewBag property to ViewBag.CategoriesDDL but then of course that's not in my model.
So for any non mvc pro's like myself here's what I did to fix that. I only changed the following in my Edit View:
@Html.DropDownList("CategoriesDDL", (IEnumerable<SelectListItem>)ViewBag.CategoriesId, new { @class = "form-control" })
To:
@Html.DropDownListFor(model => model.CategoriesId, ViewBag.CategoriesDDL as IEnumerable<SelectListItem>, new { @class = "form-control" })
Hopefully this question helps somebody out there :)