Click here to Skip to main content
15,868,071 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two dropdownlist html helper's listing two sets of enums in my razor view.
The problem is only one of the lists values are returning to the controller.
The other dropdown is returning "".

Can anyone see the problem ?
My view....
@Html.StatusDropDownListFor(model => model.Reportstatus)

Sample of my enum class...
C#
public enum Status
   {
       [Description("New Calibration")]
       New_Calibration,
       [Description("En Route to LTS Lab")]
       En_Route_to_LTS_Lab,


Used in model fro view and controller...
C#
[Display(Name = " Status")]
        public Status? Reportstatus { get; set; }


Code for custom helper...
Quote:
public static MvcHtmlString StatusDropDownListFor<tmodel,>(this HtmlHelper<tmodel> Helper, Expression<func><tmodel,>> expression)
{

ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, Helper.ViewData);
Type enumstatusType = GetNonNullableModelType(metaData);
IEnumerable<tenum> statValues = new List<tenum>();

statValues = Enum.GetValues(enumstatusType).Cast<tenum>().Where(e => e.Equals(Status.Awaiting_Onsite_Cal)
|| e.Equals(Status.En_Route_to_LTS_Lab)
|| e.Equals(Status.Finished_Calibration)
|| e.Equals(Status.New_Calibration)
|| e.Equals(Status.Received_by_LTS_from_Customer)
|| e.Equals(Status.Received_by_LTS_from_Onsite)
|| e.Equals(Status.Sent_to_3rd_Party)
|| e.Equals(Status.Sent_to_Customer)
|| e.Equals(Status.Sent_to_LTS_Lab));



IEnumerable<SelectListItem> statusitems = from value in statValues
select new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = value.Equals(metaData.Model)
};

// If the enum is nullable, add an 'empty' item to the collection
if (metaData.IsNullableValueType)
statusitems = SingleEmptyItem.Concat(statusitems);

return Helper.DropDownListFor(expression, statusitems);
}




Modelbinding...
XML
/// <summary>
    /// Binds json data to the ReportModel class. This class is required due to the MvcPaging paging HTML helper does not
    /// support sending json data via POST.
    /// </summary>
    public class ReportModelBinder : DefaultModelBinder, IModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            // creates a new model to bind data to
            ReportModel model = new ReportModel();

            string deserializedJson;

            if (GetValue(bindingContext, "paginated") != null)
            {
                // parse the json for report pages requested using the pager (json is of a serialised Newtonsoft.Json format)
                deserializedJson = GetValue(bindingContext, "paginated");
                model = JsonConvert.DeserializeObject<ReportModel>(deserializedJson);
            }
            else {
                // parse the json data for the first report page (json is of a jQuery format)
                deserializedJson = GetValue(bindingContext, "initial");

                var j = JObject.Parse(deserializedJson);

                if ( !string.IsNullOrWhiteSpace((string)j["reportTemplate"]))
                    model.ReportTemplate = (ReportType)Enum.Parse(typeof(ReportType), (string)j["reportTemplate"]);

                if ( !string.IsNullOrWhiteSpace((string)j["Reportstatus"]))
                    model.Reportstatus = (Status)Enum.Parse(typeof(Status), (string)j["Reportstatus"]);

                if( !string.IsNullOrWhiteSpace((string)j["from"]))
                    model.From = DateTime.Parse((string)j["from"]);

                if( !string.IsNullOrWhiteSpace((string)j["to"]))
                    model.To = DateTime.Parse((string)j["to"]);

                model.ReportedOn = new List<string>();

                foreach (var v in (JArray)j["reportedOn"])
                {
                    model.ReportedOn.Add((string)v);
                }

            }

            // DataAnnotation Validation
            var validationResult = from prop in TypeDescriptor.GetProperties(model).Cast<PropertyDescriptor>()
                                   from attribute in prop.Attributes.OfType<ValidationAttribute>()
                                   where !attribute.IsValid(prop.GetValue(model))
                                   select new { Propertie = prop.Name, ErrorMessage = attribute.FormatErrorMessage(string.Empty) };

            // Add the ValidationResult's to the ModelState
            foreach (var validationResultItem in validationResult)
                bindingContext.ModelState.AddModelError(validationResultItem.Propertie, validationResultItem.ErrorMessage);

            return model;
        }
Posted
Updated 30-May-14 4:45am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900