Showing posts with label MVC4. Show all posts
Showing posts with label MVC4. Show all posts

Saturday, April 25, 2015

MVC & WebAPI - Model Binder

There are some specific cases in order to use model binder to MVC and WebAPI in same project.

Here i will explain step by step to implement MVC and WebAPI Model Binders

What is Model Binder?

In some cases, we should do common operations for all actions inside controller. So in that case we can add model binder and pass as parameter to actions. In below example UserModel class sent as Model Binder

public ActionResult Index([ModelBinder]UserModel model)

{
...
}

Implementing Model Binder for MVC

MVC uses different namespace such as System.Web.Mvc. So Model Binder class also should use the same.

Step 1:

Create UserModel class as required. Here we can add our required properties. In this example, i am going to display UserId and UserName

public class UserModel
    {
        public string UserId { get; set; }
        public string UserName { get; set; }

    }

Step 2:

Create custom ModelBinder class which can be implemented from System.Web.Mvc.IModelBinder as below. Here i created as partial for merging with WebAPI. If you dont need WebAPI then just have it as normal class


public partial class UserModelBinder : System.Web.Mvc.IModelBinder
    {
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return null;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
/// Create your custom logics to fill the other required details. In this example i can fill username
            }
            return userModel;
        }
    }

Step 3:

Register this Custom ModelBinder class into Global.asax.cs file

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //Model binder for MVC controller usermodel
            ModelBinders.Binders.Add(typeof(UserModel), new UserModelBinder());

        }

Step 4:

Use this custom model binder in action methods of MVC controller

public ActionResult Index([System.Web.Http.ModelBinding.ModelBinder]UserModel model)

{
...
 //Write your logic to do with UserModel class object
}


Thats all for MVC Model Binder.


Implementing Model Binder for WebAPI

WebAPI cannot be worked with MVC model binder. So we need to create differently. Step 1 to create UserModel is same. So i will go from Step 2

Step 2:

Create Custom Model Binder for WebAPI as follows. Here IModelBinder uses System.Web.Http.ModelBinding.

using Microsoft.AspNet.Identity;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;

public partial class UserModelBinder : IModelBinder
    {
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(UserModel))
            {
                return false;
            }

            UserModel userModel = new UserModel();

            var userId = HttpContext.Current.User.Identity.GetUserId();

            if (!string.IsNullOrEmpty(userId))
            {
               //Your logic to fill usermodel class and assign to binding context’s model
                bindingContext.Model = userModel;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Error in model binding");
            return false;
        }

    }


Step 3:

Create ModelBinderProvider class as follows. It is going to be register with configuration. Here ModelBinderProvider uses namespace System.Web.Http.ModelBinding..

public class UserModelBinderProvider : ModelBinderProvider
    {
        private System.Type type;
        private UserModelBinder userModelBinder;

        public UserModelBinderProvider(System.Type type, UserModelBinder userModelBinder)
        {
            this.type = type;
            this.userModelBinder = userModelBinder;
        }

        public override IModelBinder GetBinder(HttpConfiguration configuration, System.Type modelType)
        {
            if (modelType == type)
            {
                return userModelBinder;
            }

            return null;
        }

    }


Step 4:

Register ModelBinderProvider in Global.asax.cs file under WebApiConfig register method

public static class WebApiConfig

    {
    public static void Register(HttpConfiguration config)
        {
         var provider = new UserModelBinderProvider(typeof(UserModel), new UserModelBinder());

         config.Services.Insert(typeof(ModelBinderProvider), 0, provider);


Step 5:

Use in APIController action methods as follows

[HttpGet]
        public string GetUserName([ModelBinder]UserModel model)
        {
              return model.UserName;
  }

Thats all for WebAPI Model Binder.


Tuesday, July 8, 2014

MVC Razor - DropdownListFor with index list binding

In MVC Razor, sometimes we feel selected value not reflect when we use indexed selected

Ex:    @Html.DropDownListFor(m => m.EmployeeDetails[0].StateId,
                        Model.StateList,
                        new { @class = "classname" })

in the above example state will not selected as it taken from employeeDetail list.

Change the code as below and it will work

  @Html.DropDownListFor(m => m.EmployeeDetails[0].StateId,
                        new SelectList(Model.StateList, "Value", "Text", Model. EmployeeDetails[0].StateId),
                        new { @class = "classname" })

Wednesday, June 25, 2014

MVC Razor - Enum Drop List


To Bind Enum value in Drop Down use the following

CSHTML

To display list of enum and select the value

@Html.EnumDropDownList(model => model.State, new { Id = "ddlState" })


To display list of enum item and keep binding when save/modify

@Html.EnumDropDownListFor(model => model.StateSelected, Model.State, new { Id = "ddlState" })

Note: model.StateSelected is int value.



Model

private int _StateSelected = 1;
public int StateSelected
{
  get { return _StateSelected; }
  set { _StateSelected = value; }
}


private State _State = 1;
public State State 
{
  get { return _State; }
  set { _Statevalue; }
}


Note: State is enum


public enum State
        {
            Tamilnadu =1,
            Karnadaka,
            ..
       
        }



Helper Class

  /// <summary>
        /// Enums the drop down list for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public static MvcHtmlString EnumDropDownList<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes = null)
        {

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            Type enumType = GetNonNullableModelType(metadata);
            Type baseEnumType = Enum.GetUnderlyingType(enumType);

            IEnumerable<SelectListItem> items = from value in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
                                                select new SelectListItem()
                                                {
                                                    Text = GetEnumDisplayValue(value),
                                                    Value = Convert.ChangeType(value.GetValue(null), baseEnumType).ToString(),
                                                    Selected = (value.GetValue(null).Equals(metadata.Model))
                                                };


            return SelectExtensions.DropDownList(htmlHelper, "EnumDropDown", items, htmlAttributes);

        }

        /// <summary>
        /// Enums the drop down list for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <typeparam name="TEnum">The type of the enum.</typeparam>
        /// <typeparam name="TProperty">The type of the property.</typeparam>
        /// <param name="htmlHelper">The HTML helper.</param>
        /// <param name="expression">The expression.</param>
        /// <param name="enumType">Type of the enum.</param>
        /// <param name="htmlAttributes">The HTML attributes.</param>
        /// <returns></returns>
        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, TProperty enumType, object htmlAttributes = null)
        {

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            Type baseEnumType = Enum.GetUnderlyingType(typeof(TProperty));

            IEnumerable<SelectListItem> items = from value in typeof(TProperty).GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
                                                select new SelectListItem()
                                                {
                                                    Text = GetEnumDisplayValue(value),
                                                    Value = Convert.ChangeType(value.GetValue(null), baseEnumType).ToString(),
                                                    Selected = (value.GetValue(null).Equals(metadata.Model))
                                                };

            return SelectExtensions.DropDownListFor(htmlHelper, expression, items, htmlAttributes);
        }

        /// Gets the enum display value.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <returns></returns>
        private static string GetEnumDisplayValue(FieldInfo field)
        {
            string text;

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

            if (attributes != null &&
                attributes.Length > 0)
            {
                text = attributes[0].Description;
            }
            else
            {
                text = field.Name;
            }
            return text;
        }


        /// <summary>
        /// Gets the type of the non nullable model.
        /// </summary>
        /// <param name="modelMetadata">The model metadata.</param>
        /// <returns></returns>
        private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
        {
            Type realModelType = modelMetadata.ModelType;
            Type underlyingType = Nullable.GetUnderlyingType(realModelType);

            if (underlyingType != null)
            {
                realModelType = underlyingType;
            }

            return realModelType;
        }