Related
I have a MVC web form that contains a couple textbox fields and two dropdown lists. I am trying to pass the text values of my dropdown list back to my controller to use within a method. The first dropdown list is for a location, is dependent on the second dropdown list (for security groups).
The only problem I am having is with the variable (var) value for userDn, I am trying to pass in the Location Name or "Text" value of the first dropdown list item but it is setting the location value to the switch case number of the associated with the dropdown list item instead:
Example:
Firstname: Some
Lastname: Name
Location : Temecula (switch case number 7)
currently returning: "CN=Some Name,OU=7,OU=Some OU,DC=xxx,DC=com
should return : "CN=Some Name,OU=Location Name,OU=Some OU,DC=xxx,DC=com
Am I missing a function in my javascript that would return the Text value of my first dropdown list instead of the switch case number? Any suggestions would be greatly appreciated!
public ActionResult AddUserToGroup()
{
var model = new CreateUser();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select", Value = "0" });
li.Add(new SelectListItem { Text = "Des Moines", Value = "1" });
li.Add(new SelectListItem { Text = "Fort Worth", Value = "2" });
li.Add(new SelectListItem { Text = "Kansas City", Value = "3" });
li.Add(new SelectListItem { Text = "Marysville", Value = "4" });
li.Add(new SelectListItem { Text = "South Hack", Value = "5" });
li.Add(new SelectListItem { Text = "St Clair", Value = "6" });
li.Add(new SelectListItem { Text = "Temecula", Value = "7" });
ViewData["location"] = li;
return View(model);
}
public JsonResult GetGroups(string id)
{
List<SelectListItem> groups = new List<SelectListItem>();
switch (id)
{
case "1":
groups.Add(new SelectListItem { Text = "Select", Value = "0" });
groups.Add(new SelectListItem { Text = "DM Genetec 24-7 No Act", Value = "1" });
groups.Add(new SelectListItem { Text = "DM Genetec Admin", Value = "2" });
groups.Add(new SelectListItem { Text = "DM Genetec ExtAct-Front", Value = "3" });
groups.Add(new SelectListItem { Text = "DM Genetec ExtAct-Ship", Value = "4" });
groups.Add(new SelectListItem { Text = "DM Genetec ExtAct-Ship", Value = "5" });
groups.Add(new SelectListItem { Text = "DM Genetec Front Door Inner", Value = "6" });
break;
}
return Json(new SelectList(groups, "Value", "Text"));
}
[HttpPost]
public ActionResult AddUserToGroup(CreateUser model)
{
var group = model.Group;
var location = model.Location;
var groupDn = "CN=" + group + ",OU=Groups,DC=xxx,DC=com";
var user = model.FirstName + " " + model.LastName;
var userDn = "CN=" + user + ",OU=" + location + ",OU=Some OU,DC=xxx,DC=com";
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + groupDn);
entry.Properties["member"].Add(userDn);
entry.CommitChanges();
entry.Close();
}
catch(System.DirectoryServices.DirectoryServicesCOMException E)
{
ModelState.AddModelError("", "Exception adding cool user to additional group" + E);
}
var newUserAddition = model.FirstName + " " + model.LastName;
var newGroupAddition = model.Group;
return RedirectToAction("CompletedUserToGroup", "Users", new { someNewUserAddition = newUserAddition, someNewGroupAddition = newGroupAddition });
}
--Below is the javascript in my view--
<script type="text/javascript">
$(document).ready(function () {
$("#Location").change(function () {
$("#Group").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetGroups")',
dataType: 'json',
data: { id: $("#Location").val(), Text: $("#Location").val() },
success: function (groups) {
$.each(groups, function (i, group) {
// $("#Group").append('<option value="' + group.Value + '">' + group.Text + '</option>');
$("#Group").append('<option value="' + group.Text + '">' + group.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
I figured out how to pass in the value, it seems janky but it works, in my POST ActionResult I added the following (var locationValue) after initializing var location, then I changed var userDn to: "CN=" + user + ",OU=" + locationValue + ",OU=Some OU,DC=xxx,DC=com":
var locationValue = "";
if (location == "1")
{
locationValue = "Des Moines";
}
else if (location == "2")
{
locationValue = "Fort Worth";
}
else if (location == "3")
{
locationValue = "Kansas City";
}
else if (location == "4")
{
locationValue = "Marysville";
}
else if (location == "5")
{
locationValue = "South Hack";
}
else if (location == "6")
{
locationValue = "St Clair";
}
else if (location == "7")
{
locationValue = "Temecula";
}
If you don't care about the integer value, then change Value to be the same as Text.
new SelectListItem { Text = "Des Moines", Value = "Des Moines" }
If you don't want to change the Value, then you can obtain the text label from the selected child <option>.
$("#Location option:selected").text()
The value from $("#Location").val() is automatic but the text requires finding the right child option.
I've been searching the site for a solution however, ive had no luck getting this to work. The desired end result for this piece of code will be to hide and show rows on a table with the checkboxes - the checkboxes are default set to checked as the tables by default are all shown, at the end of the code is my current method of trying to get the checkboxes to activate.
function searchContents(table, noRows) {
document.getElementById('dynamicSearchContents').innerHTML = "";
//locals declarations
var i;
var checkboxes = [];
//labels
var lables = [];
var bikesTableRows = ["Bike ID", "Bike Status", "Bike Cost", "Bike type", "Last Maintainance", "Lock Code", "Depot"];
var staffTableRows = ["Staff ID", "Fullname", "Role", "DOB", "Full Address", "Mobile", "Landline", "Email", "Notes"];
var repairTableRows = ["Repair ID", "Bike ID", "Fault", "Reported Data", "Repair Started", "Reapir Completed", "Parts Required", "Assigned Mechanic", "Repair Notes"];
var customerTableRows = ["Customer ID", "Fullname", "DOB", "Full Address", "Mobile", "Landline", "Email", "Notes"];
var collectionsTableRows = ["Job ID", "Collection Depot", "Delivery Depot", "Time and Date Started", "Time and Date Completed", "Assigned Driver"];
for (i = 0; i < noRows; i++) {
//creation
var br = document.createElement("br");
checkboxes[i] = document.createElement('input');
lables[i] = document.createElement('label');
//setting
checkboxes[i].type = "checkbox";
checkboxes[i].name = "checkbox" + i;
checkboxes[i].value = "value";
checkboxes[i].checked = "true";
checkboxes[i].class = "checkboxClass"
checkboxes[i].id = "checkbox" + i;
lables[i].htmlFor = "checkbox" + i;
//what lables
if (table === "bikeInnerTable") {
console.log("Bikes Lables")
lables[i].appendChild(document.createTextNode(bikesTableRows[i]));
}else if (table === "staffInnerTable") {
console.log("Staff Lables")
lables[i].appendChild(document.createTextNode(staffTableRows[i]));
}else if (table === "repairInnerTable") {
console.log("Repair Lables")
lables[i].appendChild(document.createTextNode(repairTableRows[i]));
}else if (table === "customerInnerTable") {
console.log("Customer Lables")
lables[i].appendChild(document.createTextNode(customerTableRows[i]));
}else if (table === "collectionsInnerTable") {
console.log("Collections Lables")
lables[i].appendChild(document.createTextNode(collectionsTableRows[i]));
}
//appending
document.getElementById('dynamicSearchContents').appendChild(lables[i]);
document.getElementById('dynamicSearchContents').appendChild(checkboxes[i]);
document.getElementById('dynamicSearchContents').appendChild(br);
}
$('.checkboxClass').on('change', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
console.log("blahahaha");
}
});
}
Edit:
A button is pressed which is located on each of the tables, it calls a function to show the search/filter div, and also the below code to populate it's contents
Pass the third argument in the jquery on function like so:
$('body').on('change', '.checkboxClass', function(){ // on change of state
if(this.checked) // if changed state is "CHECKED"
{
console.log("blahahaha");
}
});
}
This will bind any future elements with '.checkboxClass' that are created to this same function.
I am trying to Create Cascading data table using java script but it's not printing data properly.
I want to crete drop down when I select asset from dropdown , it load all section name from that asset and when I select sections fron thier child it select Ultrasonic sections name.
Also in asset it's populating 4 time "asset 4". It should print 1 time only.
I tried to debuge but it's not working . can any one help me?
And I want to do this in JavaScript only
JAVASCRIPT
var stateObject = '{"uri": "/assets/4afd3544-cea1-363d-ba29 e39831d8930d","name": "Asset 4","sections": [{"uri": "/assets/2dc11152-7b85- 35d7-8af6-c48ca4397d9f","sectionId": null, "name": "Section 1","ultrasonicSensors": null,"temperatureSensors": null,"ultrasonicSensorPositions": [{"ultrasonicSensorPositionId":"1395","sensorPositionName":"MeasurementPosition 1","diameter": "0","rotation": "0","sequenceNumber": null, "sectionId": "/assets/2dc11152-7b85-35d7-8af6-c48ca4397d9f"}]}]}';
var json = JSON.parse(stateObject);
window.onload = function () {
var stateSel = document.getElementById("stateSel"),
countySel = document.getElementById("countySel"),
citySel = document.getElementById("citySel");
for (state in json) {
stateSel.options[stateSel.options.length] = new Option(json.name , "");
}
stateSel.onchange = function () {
countySel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) {
countySel.options[0].text = "Please select state first"
citySel.options[0].text = "Please select county first"
return; // done
}
countySel.options[0].text = "Please select county"
var x = JSON.stringify(json.sections);
// alert(x)
for (var county in x) {
countySel.options[countySel.options.length] = new Option(county, x);
}
if (countySel.options.length==2) {
countySel.selectedIndex=1;
countySel.onchange();
}
}
stateSel.onchange(); // reset in case page is reloaded
countySel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) {
citySel.options[0].text = "Please select county first"
return; // done
}
citySel.options[0].text = "Please select city"
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
if (citySel.options.length==2) {
citySel.selectedIndex=1;
citySel.onchange();
}
}
}
Here is js fiddle demo
I am trying to add a DropDown list to a custom sharepoint ribbon bar tab using javascript, I know that this is not the recommended way and that I should use the declarative approach. I have managed to create Tabs, Groups and add buttons to them, but for some reason createing a dropdown does nothing and gives no errors.
here are the functions that I use to create the tab elements
function CreateCustomTab(tabName, tabTitle, tabGroup, tabToolTip) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var tab;
if (ribbon !== null) {
tab = new CUI.Tab(ribbon, tabName + ".Tab", tabTitle, tabToolTip, tabName + ".Tab.Command", false, '', null);
ribbon.addChild(tab);
}
return tab
}
function CreateTabGroup(tab, tabName, groupTitle, groupToolTip) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var group = new CUI.Group(ribbon, tabName + ".Tab.Group", groupTitle, groupToolTip, tabName + ".Group.Command", "test");
tab.addChild(group);
return group;
}
function CreateLayout(group, tabName, LayoutTitle) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var layout = new CUI.Layout(ribbon, tabName + ".Tab.Layout", LayoutTitle);
group.addChild(layout);
return layout;
}
function CreateDropDownList(tabName, layout, layoutTitle, listName, toolTip, listLabel, ToolTipTitle) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var section = new CUI.Section(ribbon, tabName + ".Tab.Section", 2, "Top"); //2==One Row
layout.addChild(section);
var controlProperties = new CUI.ControlProperties();
controlProperties.Command = listName + ".DropDown.Command";
controlProperties.Id = listName + ".ControlProperties";
controlProperties.TemplateAlias = "o1";
controlProperties.ToolTipDescription = toolTip;
// controlProperties.Image32by32 = (Image32by32RelativePath ? Image32by32RelativePath : '_layouts/15/images/placeholder32x32.png');
controlProperties.ToolTipTitle = ToolTipTitle;
controlProperties.LabelText = listLabel;
var dropDown = new CUI.Controls.DropDown(ribbon, listName + ".DropDown", controlProperties, ["Test1","Test2","Test3"]);
var controlComponent = dropDown.createComponentForDisplayMode('Large');
var row1 = section.getRow(1);
row1.addChild(controlComponent);
}
function CreateButton(tabName, layout, layoutTitle, buttonName, toolTip, buttonText, ToolTipTitle, Image32by32RelativePath) {
var ribbon = SP.Ribbon.PageManager.get_instance().get_ribbon();
var section = new CUI.Section(ribbon, tabName + ".Tab.Section", 2, "Top"); //2==One Row
layout.addChild(section);
var controlProperties = new CUI.ControlProperties();
controlProperties.Command = buttonName + ".Button.Command";
controlProperties.Id = buttonName + ".ControlProperties";
controlProperties.TemplateAlias = "o1";
controlProperties.ToolTipDescription = toolTip;
controlProperties.Image32by32 = (Image32by32RelativePath ? Image32by32RelativePath : '_layouts/15/images/placeholder32x32.png');
controlProperties.ToolTipTitle = ToolTipTitle;
controlProperties.LabelText = buttonText;
var button = new CUI.Controls.Button(ribbon, buttonName + ".Button", controlProperties);
//var controlComponent = new CUI.ControlComponent(ribbon, buttonName + ".MenuItem.Button", "Large",button)
var controlComponent = button.createComponentForDisplayMode('Large');
var row1 = section.getRow(1);
row1.addChild(controlComponent);
}
and here is how these are called
SP.SOD.executeOrDelayUntilScriptLoaded(function () {
var pm = SP.Ribbon.PageManager.get_instance();
pm.add_ribbonInited(function () {
var tab = CreateCustomTab("SomeTab", "Some Tab", "View Format", "Use this tab");
var group = CreateTabGroup(tab, "SomeTab", "View Format", "Switch between");
var layout = CreateLayout(group, "SomeTab", "SomeTabLayout");
CreateButton("SomeTab", layout, "SomeTabLayout", "ListViewButton", "Switch to list view, this displays a grid with the items ungrouped in an editable table!", "List View", "Table List View");
CreateButton("SomeTab", layout, "SomeTabLayout", "HierarchyButton", "Switch to tree view, this displays a grid with the items grouped in a parent child relationship!", "Tree View","Hierarchy view");
var hierarchyEditGroup = CreateTabGroup(tab, "SomeTab", "Hierarchy Edit", "Edit hierarchy");
var hierarchyLayout = CreateLayout(hierarchyEditGroup, "SomeTab", "HierarchyLayout");
CreateButton("SomeTab", hierarchyLayout, "HierarchyLayout", "EditHierarchyButton", "Edit current hierarchy", "Edit Tree", "Edit current hierarchy");
var ViewsGroup = CreateTabGroup(tab, "ISSQeueuListTab", "Views", "Change data views");
var ViewsLayout = CreateLayout(ViewsGroup, "SomeTab", "ViewsLayOut");
CreateDropDownList("SomeTab", ViewsLayout, "Current View", "DataViewList", "Change the the current view from the available public and private views", "Current View", "View Selection");
group.selectLayout("SomeTabLayout");
hierarchyEditGroup.selectLayout("HierarchyLayout");
SelectRibbonTab("SomeTab.Tab", true);
SelectRibbonTab("Ribbon.Read", true);
$("#Ribbon\\.WebPartPage-title").hide();
var Commands = [];
Commands.push({ name: "SomeTab.Tab.Command", enabled: true, handler: function (a, b, c) { } });
Commands.push({ name: "SomeTab.Group.Command", enabled: true, handler: function (a, b, c) { } });
Commands.push({ name: "DataViewList.DropDown.Command", enabled: true, handler: function () { }});
Commands.push({
name: "HierarchyButton.Button.Command", enabled: true, handler: function (CommandID, properties, seq) {
AppFrame.contentWindow.postMessage("ShowTreeView()", "*");
var Ribbon = SOMESpAppSPPage.get_instance();
var button = Ribbon.GetCommand("EditHierarchyButton.Button.Command");
button.enabled = true;
RefreshCommandUI();
}
});
Commands.push({
name: "ListViewButton.Button.Command", enabled: true, handler: function (CommandID, properties, seq) {
AppFrame.contentWindow.postMessage("ShowListView()", "*")
var Ribbon = SOMESpAppSPPage.get_instance();
var button = Ribbon.GetCommand("EditHierarchyButton.Button.Command");
button.enabled = false;
RefreshCommandUI();
}
});
Commands.push({
name: "EditHierarchyButton.Button.Command", enabled: false, handler: function (CommandID, properties, seq) {
AppFrame.contentWindow.postMessage("ShowHierarchyEdit()", "*");
}
});
SOMESpAppSPPage.initializePageComponent(Commands);
});
var ribbon = null;
try {
ribbon = pm.get_ribbon();
}
catch (e) { }
if (!ribbon) {
if (typeof (_ribbonStartInit) == "function")
_ribbonStartInit(_ribbon.initialTabId, false, null);
}
else {
CreateCustomTab("SomeTab", "SOMESpApp List", "SOMESpAppTabGroup", "Use this tab to intertact with the ISS Queue");
}
}, "sp.ribbon.js");
I had to change some of the names of the variables, but this is exact code I am using. the buttons and tabs work but the Drop down will not any one have an idea.
Change the TemplateAlias for the control in "function CreateDropDownList" from "o1" to "o2" and I speculate this will start working:
controlProperties.TemplateAlias = "o2";
I have a slight problem here that each time I run the application the first radio button is always checked, I want to make nun of the radio buttons checked. How do I do this?
<div class="col-md-12">
<!--<i class="fa fa-child" aria-hidden="true"></i>-->
#Html.LabelFor(model => model.CCommmunication, "Choose your preferred way of communication", new { #style = "", #class = "", id = "" })
<span style="color: red;">*</span>
#*#Html.DropDownListFor(model => model.Profession, new SelectList(Model.Professions, "Id", "Name"), new { placeholder = "", #style = "", #class = "form-control", id = "Profession" })*#
#Html.EnumRadioButtonFor(model => model.CCommmunication, false,false,"communicationCB") <!--first 2 paramerters are false false communicationCB is the class-->
#Html.ValidationMessageFor(model => model.CCommmunication)
</div>
this is my Model
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication CCommmunication
{ get; set; }
public enum Commmunication
{
[Display(Name = "Email", Order = 0)]
Email,
[Display(Name = "Mobile telephone", Order = 1)]
TelephoneNo,
[Display(Name = "Alternative telephone", Order = 2)]
TelephoneNoAlternative
}
This is my JavaScript
<script>
var checkedVal = $('.communicationCB input[name=CCommmunication]:checked').val(); //Added a variable to check the value
if (checkedVal == "TelephoneNo") { //if checked valuie
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
};
if (checkedVal == "TelephoneNoAlternative") { //if checked valuie == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
};
$('.communicationCB input[name=CCommmunication]').click(function () { //.communication class passed input name == model public communication
if ($(this).val() == "TelephoneNo") { //if value TelephoneNo selected in model
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
}
if ($(this).val() == "TelephoneNoAlternative") { //if value == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
}
});
Finally I have a enumRadioButton.cs
public static class HtmlHelper
{
public static MvcHtmlString EnumRadioButtonFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
bool includeNoneOption = true,
bool isDisabled = false,
string cssClass = null
) where TModel : class
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
throw new InvalidOperationException("Expression must be a member expression");
var name = ExpressionHelper.GetExpressionText(expression);
var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
ModelState currentValueInModelState;
var couldGetValueFromModelState = htmlHelper.ViewData.ModelState.TryGetValue(fullName, out currentValueInModelState);
object selectedValue = null;
if (couldGetValueFromModelState && htmlHelper.ViewData.Model != null)
{
selectedValue = expression.Compile()(htmlHelper.ViewData.Model);
}
var enumNames = GetSelectItemsForEnum(typeof(TProperty), selectedValue).Where(n => !string.IsNullOrEmpty(n.Value)).ToList();
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
sb.AppendFormat(
"<ul class=\"radio-button-list{0}\">",
string.IsNullOrEmpty(cssClass) ? string.Empty : " " + cssClass);
foreach (var enumName in enumNames)
{
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
enumName.Value
);
if (id.StartsWith("-"))
id = id.Remove(0, 1);
var value = enumName.Value;
sb.AppendFormat(
//"<li>{2} <label for=\"{0}\">{1}</label></li>", //Originol puts data in a list
"{2} <label for=\"{0}\">{1}</label>",
id,
HttpUtility.HtmlEncode(enumName.Text),
isDisabled
? htmlHelper.RadioButtonFor(expression, value, new { id, disabled = "disabled" }).ToHtmlString()
: htmlHelper.RadioButtonFor(expression, value, new { id }).ToHtmlString()
);
}
sb.Append("</ul>");
return MvcHtmlString.Create(sb.ToString());
}
public static IList<SelectListItem> GetSelectItemsForEnum(Type enumType, object selectedValue)
{
var selectItems = new List<SelectListItem>();
if (enumType.IsGenericType &&
enumType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
enumType = enumType.GetGenericArguments()[0];
selectItems.Add(new SelectListItem { Value = string.Empty, Text = string.Empty });
}
var selectedValueName = selectedValue != null ? selectedValue.ToString() : null;
var enumEntryNames = Enum.GetNames(enumType);
var entries = enumEntryNames
.Select(n => new
{
Name = n,
DisplayAttribute = enumType
.GetField(n)
.GetCustomAttributes(typeof(DisplayAttribute), false)
.OfType<DisplayAttribute>()
.SingleOrDefault() ?? new DisplayAttribute()
})
.Select(e => new
{
Value = e.Name,
DisplayName = e.DisplayAttribute.Name ?? e.Name,
Order = e.DisplayAttribute.GetOrder() ?? 50
})
.OrderBy(e => e.Order)
.ThenBy(e => e.DisplayName)
.Select(e => new SelectListItem
{
Value = e.Value,
Text = e.DisplayName,
Selected = e.Value == selectedValueName
});
selectItems.AddRange(entries);
return selectItems;
}
}
}
To have none of the radio buttons selected, you make the property nullable
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication? CCommmunication { get; set; }
If CCommmunication has an initial value of null, then no radio buttons will be selected.
But its unclear what you trying to do with all that (unnecessary) code in you extension method, in particular why you are creating IList<SelectListItem> (which is for generating a <select> tag). Your helper can simply be
public static class RadioButtonHelper
{
public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
Type type = Nullable.GetUnderlyingType(metaData.ModelType);
if (type == null || !type.IsEnum)
{
throw new ArgumentException(string.Format("The property {0} is not an enum", name));
}
StringBuilder html = new StringBuilder();
foreach (Enum item in Enum.GetValues(type))
{
string id = string.Format("{0}_{1}", metaData.PropertyName, item);
StringBuilder innerHtml = new StringBuilder();
innerHtml.Append(helper.RadioButtonFor(expression, item, new { id = id }));
innerHtml.Append(helper.Label(id, item.ToDescription()));
TagBuilder div = new TagBuilder("div");
div.AddCssClass("radiobutton");
div.InnerHtml = innerHtml.ToString();
html.Append(div.ToString());
}
TagBuilder container = new TagBuilder("div");
container.AddCssClass("radiobutton-container");
container.InnerHtml = html.ToString();
return MvcHtmlString.Create(container.ToString());
}
}
which uses the following extension method
public static class EnumExtensions
{
public static string ToDescription(this Enum value)
{
if (value == null)
{
return null;
}
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return value.ToString();
}
}
in association with the [Description] attribute applied to your enum values rather that the [Display] attribute (but you can easily modify that)