MVC RadioButtonList


/ Published in: C#
Save to your folder(s)

Code snippet that allows developers to use a generic radiobuttonlist in the MVC Framework


Copy this code and paste it in your HTML
  1. public static partial class HtmlHelpers
  2. {
  3. public static void ShowRadioButtonList<T>(this ViewPage page, IList<string> list, string name, Expression<Func<T, object>> valueProperty, Expression<Func<T, object>> displayProperty, string selectedValue, System.Web.UI.WebControls.Orientation orientation)
  4. {
  5. HtmlTextWriter writer = new HtmlTextWriter(page.Response.Output);
  6. if (writer != null)
  7. {
  8. for (int i = 0; i < list.Count; i++)
  9. {
  10. string value = list[i];
  11. writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio");
  12. writer.AddAttribute(HtmlTextWriterAttribute.Id, name + "_" + i);
  13. writer.AddAttribute(HtmlTextWriterAttribute.Name, name, true);
  14. writer.AddAttribute(HtmlTextWriterAttribute.Value, value, true);
  15. if (value == selectedValue)
  16. writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
  17.  
  18. writer.RenderBeginTag(HtmlTextWriterTag.Input);
  19. writer.Write(value);
  20. writer.RenderEndTag();
  21.  
  22. if (orientation == System.Web.UI.WebControls.Orientation.Vertical)
  23. {
  24. writer.RenderBeginTag(HtmlTextWriterTag.Br);
  25. writer.RenderEndTag();
  26. }
  27. }
  28. }
  29. }
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.