Reputation: 10712
I'm trying to create an editor template that will create a "bootstrap style" radio buttons for each value from a passed select list (just like the Html.DropDownFor
method create a dropdown list)
So i have the call in my view:
@Html.EditorFor(model => model.FaultTypeID,"RadioButtonList",
new SelectList(Model.AllowdeFaultTypes, "FaultTypeID", "FaultTypeName"))
and now the template of RadioButtonList:
@foreach (var item in ViewData["Items"] as SelectList)
{
<a>@item.Text</a> <b>@item.Value</b>
}
but the conversion fails and i get a NullReferanceExeption
.
By reflection i see that the ViewData["Items"]
value is of type System.Collections.Generic.List<CamelotFaultManagement.DAL.FaultType>
The problem is i really don't want to tightly couple the RadioButtonList
editor template with CamelotFaultManagement.DAL.FaultType
class, its just don't make any sense to do that. I want a generic editor template.
Upvotes: 3
Views: 2791
Reputation: 1038710
In your editor template you seem to be using some ViewData["Items"]
property which you never set. If you want to use such property make sure you have assigned it:
@Html.EditorFor(
model => model.FaultTypeID,
"RadioButtonList",
new { Items = new SelectList(Model.AllowdeFaultTypes, "FaultTypeID", "FaultTypeName") }
)
This being said, your approach with using some ViewData stuff seems totally wrong to me.
I would simply define a view model (as always in ASP.NET MVC):
public class RadioListViewModel
{
public string Value { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
}
and then you could have your editor template strongly typed to this view model. Of course your editor template will be now stored in ~/Views/Shared/EditorTemplates/RadioListViewModel.cshtml
:
@model IRadioListViewModel
@foreach (var item in Model)
{
<a>@item.Text</a> <b>@item.Value</b>
}
and now all that's left is to use this view model in your main view model:
public class MyViewModel
{
public RadioListViewModel FaultTypes { get; set; }
...
}
and then inside your view simply render the corresponding editor template:
@model MyViewModel
...
@Html.EditorFor(x => x.FaultTypes)
Simple, conventional, strongly typed.
Upvotes: 7