Joseph Michael Pesch
VP Programming

ASP.Net MVC Bind Boolean to DropDownList Using @Html.DropDownListFor

by 25. June 2014 07:41

I was having difficulty binding a bool property to a DropDownList using the @Html.DropDownListFor() method.  What ended up working well was to do the following:

 

Add this to the View Controller class:

private void Select_YN_Rebind()
{
  List<SelectListItem> Select_YN = new List<SelectListItem>();
  Select_YN.Add(new SelectListItem
  {
    Text = "No",
    Value = bool.FalseString
  });
  Select_YN.Add(new SelectListItem
  {
    Text = "Yes",
    Value = bool.TrueString
  });
  ViewData["Select_YN"] = Select_YN;
}


Add call to the new method in the View Controller Create method (or whatever other method is appropriate) before returning the view:

public ActionResult Create()
{
  Select_YN_Rebind();
  return View();
}

Call the @Html.DropDownListFor() as shown below:

 @Html.DropDownListFor(model => model.YourBoolPropertyHere
, (IEnumerable<SelectListItem>)ViewData["Select_YN"])

 

Tags:

ASP.Net | MVC

ASP.Net MVC 5 Issue Validating Numbers (Decimal) when Number Contains Commas

by 20. June 2014 11:37

ASP.Net MVC 5 number (decimal) validation failing when user entered data contains commas.  To get around this issue I created a custom

Create the following object and bind it in the Global.asax as shown below.  NOTE: For javascript client side validations create a new *.js file and make sure to include it AFTER the jquery.validate* in the BundleConfig.cs.

JAVASCRIPT OVERRIDE

$.validator.methods.range = function (value, element, param) {
  var globalizedValue = value.replace(",", ".");
  return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
}
$.validator.methods.number = function (value, element) {
  return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
};

GLOBAL.ASAX ADDITION

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

NEW .CS FILE

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyApp.Models.Binders
{
  public class DecimalModelBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
      ValueProviderResult valueResult = bindingContext.ValueProvider
          .GetValue(bindingContext.ModelName);
      ModelState modelState = new ModelState { Value = valueResult };
      object actualValue = null;
      try
      {
        //Check if this is a nullable decimal and a null or empty string has been passed
        var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
                                 string.IsNullOrEmpty(valueResult.AttemptedValue));

        //If not nullable and null then we should try and parse the decimal
        if (!isNullableAndNull)
        {
          actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
        }
      }
      catch (FormatException e)
      {
        modelState.Errors.Add(e);
      }

      bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
      return actualValue;
    }
  }
}

Tags:

ASP.Net | MVC

ASP.Net MVC 5 Issue Validating Numbers (Decimal) when Number Contains Commas

by 20. June 2014 11:37

ASP.Net MVC 5 number (decimal) validation failing when user entered data contains commas.  To get around this issue I created a custom

Create the following object and bind it in the Global.asax as shown below.

GLOBAL.ASAX

ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());

NEW .CS FILE

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyApp.Models.Binders
{
  public class DecimalModelBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
      ValueProviderResult valueResult = bindingContext.ValueProvider
          .GetValue(bindingContext.ModelName);
      ModelState modelState = new ModelState { Value = valueResult };
      object actualValue = null;
      try
      {
        //Check if this is a nullable decimal and a null or empty string has been passed
        var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
                                 string.IsNullOrEmpty(valueResult.AttemptedValue));

        //If not nullable and null then we should try and parse the decimal
        if (!isNullableAndNull)
        {
          actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture);
        }
      }
      catch (FormatException e)
      {
        modelState.Errors.Add(e);
      }

      bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
      return actualValue;
    }
  }
}

Tags:

ASP.Net