Archive

Archive for April, 2014

MVC3 Load enumerator in a dropdown and set as selected in edit mode

April 29, 2014 Leave a comment

ViewModel class: Syntax: In your view model calss make 2 properties
—————
[Display(Name = “Fee Type”)]
[Required]
public SchoolApp.EnumValues.FeeTypeValues FeeType { get; set; }

public List<SelectListItem> FeeTypeOptions { get; set; }

Controller
———
FeeHeaderModel model = new FeeHeaderModel();
model.FeeTypeOptions = getFeeTypeOptions();

public List<SelectListItem> getFeeTypeOptions()
{
    string[] names = Enum.GetNames(typeof(FeeTypeValues)); //ur enum vvalues here
    List<SelectListItem> _licenceItems = new List<SelectListItem>();
    foreach (string _value in names)
    {
        _licenceItems.Add(new SelectListItem
        {
            Text = _value,
            Value = _value
        });
    }
    return _licenceItems;
}

In edit mode set selected value by using the below code
try
{
    model.FeeType = (SchoolApp.EnumValues.FeeTypeValues)Enum.Parse(typeof(SchoolApp.EnumValues.FeeTypeValues), dbItem.FeeType, true);
}
catch
{
    model.FeeType = SchoolApp.EnumValues.FeeTypeValues.Common;
}        
        
Razor view syntax:
————
<div class=”form-group”>
    @Html.LabelFor(model => model.FeeType)      
    @Html.DropDownListFor(model => model.FeeType,Model.FeeTypeOptions, new { @class = “form-control” })
    @Html.ValidationMessageFor(model => model.Amount)
</div>

Advertisements
Categories: Prsnl References Tags: