I am trying to generate a list as follows-
@using SkyTracker.Models
@model SkyTracker.Models.Outlet
@{
var outletTypeList = new List<SelectListItem>();
foreach (var item in ViewBag.OutletTypes)
{
//Exception Cannot implicitly convert type 'int' to 'string'
var newType = new SelectListItem { Text = item.OutletTypeName, Value = item.OutletTypeId };
outletTypeList.Add(newType);
}
}
<form method="post" action="@(ViewBag.BaseUrl)OutletManagement/[email protected]">
@Html.LabelFor(m => m.OutletTypeId, new { @class="required"})
@Html.DropDownListFor(m => m.OutletTypeId, outletTypeList, new {required="required" })
</form>
But I'm gettting an exception in the foreach loop. Any help?
The
Value
property ofSelectListItem
is tyeofstring
so ifOutletTypeId
is typeofint
, then useValue = item.OutletTypeId.ToString()
.However that code belongs in the controller, not the view, and ideally you should be using a view model that contains a property
IEnumerable<SelectListItem> OutletTypeList
and in the controller
and in the view
Note also that you should remove
new {required="required" }
which is HTML5 client side validation only and add aRequiredAttribute
to the property your binding to so that you get both client and server side validation.Consider also using
to generate the form element