andtodd
andtodd

Reputation: 240

Adding attributes to MVC Select List

I am creating a select list in my MVC application and need to replicate something that is written in HTML.

I have the following code which currently gets the data from the model and produces the select list with options for each item in the model, including the JobID as the Value, WebDescription as the text and uses category to categorise the items in the drop down.

var basketDetails = new SelectList(items.basketJobCodes, "jobID", "WebDescription", "category", 1);

List<SelectListItem> basketItems = basketDetails.ToList();

basketItems.Insert(0, (new SelectListItem { Text = "-- Please pick an item for collection --", Value = "none", Selected = true }));

@Html.DropDownList("basket-item", basketItems, new { @id = "edit-basket-item", @class = "form-select"})

The current version has an extra attribute on each drop down item called itemCat which gives a number used to categorise each item (see below), however I can't figure out how to add the attribute to my selectlist and get the value from the model as I have done with the JobID, WebDescription and category.

<optgroup label="1 for £10">
@foreach (var item in ViewBag.largeJobs)
{ 
<option value="@item.jobID" itemCat="@item.bags"@item.WebDescription</option>
}
</optgroup>

Any ideas?

Upvotes: 0

Views: 561

Answers (1)

Charanjit Singh
Charanjit Singh

Reputation: 59

Here is the easy solution.

With MVC4 you can get the id and name of the element on the expression tree with the helpers HTML.NameFor and HTML.IdFor

<select name="@Html.NameFor(Function(model) model.jobId)"
        id="@Html.IdFor(Function(model) model.jobId)">
    @For Each item In ViewBag.largeJobs
        @<option value="@item.jobID"
                 @(If(item.jobID = Model.CityId, "selected", ""))
                 itemCat="@item.bags">
            @item.WebDescription
        </option>
    Next
</select>

Upvotes: 1

Related Questions