Friday 22 November 2013

Using Text Description in Enumeration Type

If we would like to have text description for an enum, we could use Description attribute like below:
public enum MyEnum
{
 [Description("Value One")]
 One,

 [Description("Second Value")]
 Two
};

Then to get the description text we could use something like the codes below. Usually we would put this in a helper class.
public static string GetEnumDescription(Enum value)
{
 FieldInfo fi = value.GetType().GetField(value.ToString());

 DescriptionAttribute[] attributes =
  (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

 if (attributes != null && attributes.Length > 0)
  return attributes[0].Description;
 else
  return value.ToString();
}

Finally the usage:
Helper.GetEnumDescription(MyEnum.Two);


Reference:
http://blog.spontaneouspublicity.com/associating-strings-with-enums-in-c

Friday 15 November 2013

Using Editor Template for Rendering DropDownList

Below is an example of how to have a dropdownlist when editing a model that has an integer type property used for foreign key property. I.e.; I have a model that has this property:
int ItemId { get; set; }
Then I want every time an instance of this model type is being edited, the field is shown as a dropdownlist. To do this, inside 'EditorTemplates' folder under the global 'Views\Shared' or a view's specific folder, I create a partial view named 'Item.cshtml' like below:
@Html.DropDownListFor(model => ViewData.TemplateInfo.FormattedModelValue, ((IEnumerable<Model.Item>)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name, 
                Value = option.ItemId.ToString(),
                Selected = (Model != null) && (option.ItemId == (int)ViewData.TemplateInfo.FormattedModelValue)
            }), "Please select")
Note that, I use ViewData.TemplateInfo.FormattedModelValue to get the value. I could also write like this by declaring the model to use:
@model int

@Html.DropDownListFor(model => model, ((IEnumerable<Model.Item>)ViewBag.Items).Select(option => new SelectListItem {
                Text = option.Type.Name, 
                Value = option.ItemId.ToString(),
                Selected = option.ItemId == Model
            }), "Please select")
Then to render the custom template on my edit view page, I do:
@Html.EditorFor(model => model.ItemId, "Item")

For more details about Editor Template or Display Template, you could see my previous post.