How to add additional fields when using Membership in ASP.NET MVC 4

1. Modify your UserProfile class

Here in this example I am adding a new field called “MobileNumber“, have declared it as type string.

public class UserProfiles
    public int UserId { get; set;}
    public string Email { get; set;}
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MobileNumber { get; set; }

2. Add the additional property(ies) to your RegisterModel.cs

Add the new property in your Model. In this example where we want an extra field while user registration we need to update the RegisterModel class. Add validations if need be.

public class RegisterModel
    [Display(Name = "Email")]
    public string Email { get; set; }

    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [StringLength(11, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 11)]
    [Display(Name = "Mobile No.")]
    public string MobileNumber { get; set; }


3. Display additional fields on your View

Once you have update the Model you should be able to use the @Html.TextBoxFor(m => m.MobileNumber) in your view, which will bind the MobileNumber field to your ‘MobileNumber’ property declared in your model.

@using (Html.BeginForm()) {

    @Html.LabelFor(m = m.Email)
    @Html.TextBoxFor(m => m.Email)

    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password)

    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)

    @Html.LabelFor(m => m.LastName)
    @Html.TextBoxFor(m => m.LastName)

    @Html.LabelFor(m => m.MobileNumber)
    @Html.TextBoxFor(m => m.MobileNumber)

    <input type="submit" value="Register">

4. Update your Controller – (AccountController in this case)

Last step, here you just need to read the value posted to your model and pass it along the repository for saving.

public ActionResult Register(RegisterModel model)
    if (ModelState.IsValid)
        // Attempt to register the user
            WebSecurity.CreateUserAndAccount(model.Email, model.Password,
                                                     FirstName = model.FirstName,
                                                     LastName = model.LastName,
                                                     MobileNumber = model.MobileNumber
            WebSecurity.Login(model.Email, model.Password);
            return RedirectToAction("Index", "Home");
        catch (MembershipCreateUserException e)
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));

    // If we got this far, something failed, redisplay form
    return View(model);

Flat UI theme for ASP.NET MVC Web App

Nowadays Flat UI has become very popular with any developers and desginers, all major websites, web app and even mobile apps have shifted to Flat UI.

I recently saw this Flat UI – Free User Interface Kit and I created this template for ASP.NET MVC built website. The code has been downloaded for view from here GitHub – Flat-UI-Template-ASP.NET-MVC and can also demo it here.

Below are few screenshots from the template :




Custom Authorization in ASP.NET MVC 3 using IAuthorizationFilter & FilterAttribute

Authorization filters : These implement IAuthorizationFilter and make security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

This post demonstrates how to create a custom authorization filter.

Step 1 : Create the Authorization Attribute and Filter:

///marker attribute
public class CustomAuthorizeAttribute : FilterAttribute { }

public class CustomAuthorizeFilter : IAuthorizationFilter
      private readonly ICustomerService _customerService;
      public CustomAuthorizeFilter(ICustomerService userService)
          _customerService = userService;

      public override void OnAuthorization(AuthorizationContext filterContext)
          var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
          var actionName = filterContext.ActionDescriptor.ActionName;

          var authorized = false;
          var routeValues = GetRouteDataValues();
          int id = routeValues["id"] == null ? 0 : int.Parse(routeValues["id"].ToString());

          // build your custom logic using 
          // controllerName, actionName and id to set the 'authorized' flag.


    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
          Raise(new Exception("403 forbidden - " + filterContext.RequestContext.HttpContext.Request.RawUrl, null));
        filterContext.HttpContext.Response.StatusCode = 404;
        filterContext.Result = new ViewResult
            ViewName = "~/Views/Error/PageNotFound.cshtml"

      public Dictionary<string, object> GetRouteDataValues()
          return new Dictionary<string, object>(_contextBase.Request.RequestContext.RouteData.Values);

Step 2: Binding:

this.BindFilter<CustomAuthorizeFilter>(System.Web.Mvc.FilterScope.Controller, 0).WhenActionHas<CustomAuthorizeAttribute>();

Step 3 : Decorate your Actions with the filter:

public class AccountController : Controller
    public ActionResult MyPreciousAction()
        // beep beep bepp ;)

You may want to refer the below links I had used while creating this blog post. Cheers !


Using Custom Validation Attributes in ASP.NET MVC


Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

Below is the code for the same, its pretty self-explanatory. In case of doubts or queries feel free to use the comments section.

public class EmployeeModel 
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
    private IEmployeeRepository _employeeRepository;
    public IEmployeeRepository EmployeeRepository
        get { return _employeeRepository; }
            _employeeRepository = value;
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
        var message = "Email address already in use in this organization.";
        var model = (EmployeeModel)validationContext.ObjectInstance;
        var spec = new Specification<EmployeeModel>
        (m => m.EmailAddress == value && m.OrganizationId == model.OrganizationId);
        var emp = _employeeRepository.Get(spec);
        if(emp != null)
            return new ValidationResult(message);
        return ValidationResult.Success;

Hope this helps. Cheers !


Introduction to RabbitMQ with C# .NET, ASP.NET and ASP.NET MVC with examples

This post assumes that you already have installed and configured RabbitMq on your system or on some server. Download .NET/C# RabbitMq’s client library from or from

If RabbitMq has been installed on your server, you can view the management screen using this url : http://server-name:15672/, more on this you will find on this link.

Incase you havent read about what RabbitMq is and how it works I strongly recommend you to read the following links first and then come back again to this post.

Lets get started, first you’ll need to import the libraries(dll) u just downloaded.


You can use the following class I have created, modify them to suit your requirement. Instead of hard-coding the Username, Password and other fields its better you define them in your config file and read from there.

public static class BrokerHelper
    public static string Username = "guest";
    public static string Password = "guest";
    public static string VirtualHost = "/";
    // "localhost" if rabbitMq is installed on the same server,
    // else enter the ip address of the server where it is installed.
    public static string HostName = "localhost";
    public static string ExchangeName = "test-exchange";
    public static string ExchangeTypeVal = ExchangeType.Direct;
    public static string QueueName = "SomeQueue";
    public static bool QueueExclusive = false;
    public static bool QueueDurable = false;
    public static bool QueueDelete = false;
    public static string RoutingKey = "yasser";

    public static IConnection Connection;
    public static IModel Channel;
    public static void Connect()
        var factory = new ConnectionFactory();
        factory.UserName = Username;
        factory.Password = Password;
        factory.VirtualHost = VirtualHost;
        factory.Protocol = Protocols.FromEnvironment();
        factory.HostName = HostName;
        factory.Port = AmqpTcpEndpoint.UseDefaultPort;
        Connection = factory.CreateConnection();
        Channel = Connection.CreateModel();

    public static void Disconnect()
        Connection.Close(200, "Goodbye");

    public static bool IsBrokerDisconnected()
        if(Connection == null) return true;
        if(Connection.IsOpen) return false;
        return true;

    public static void Publish(string message)
        if (IsBrokerDisconnected()) Connect();

        Channel.ExchangeDeclare(ExchangeName, ExchangeTypeVal.ToString());
        Channel.QueueDeclare(QueueName, QueueDurable, QueueExclusive, QueueDelete, null);
        Channel.QueueBind(QueueName, ExchangeName, RoutingKey);
        var encodedMessage = Encoding.ASCII.GetBytes(message);
        Channel.BasicPublish(ExchangeName, RoutingKey, null, encodedMessage);

Almost Done ! Now that we have the above classes in place, publishing our message to rabbitMq will just be the following line of code :

BrokerHelper.Publish("Hello World");

Hope this helped.


Using Twitter typeahead.js with ASP.NET MVC Web API

There are many auto-complete jQuery libraries I have used before, like jQuery UI’s Autocomplete, loopJ’s jQuery Tokeninput and Select2. But one of my colleague at work, recently introduced me to this jQuery plugin called twitter’s typeahead.js, it seemed to be good, so we decided to use it in one of our ongoing project.

So, What is typeahead.js ? typeahead.js is a fast and fully-featured autocomplete library. You can check out some of the basic examples from here or you can hit straight to the docs from here.

Lets get started with a few basic examples.

1. Things you’ll need to download: You can download the latest version of typeahead.js from here. Below are the js and css you’ll need to include :

<script src="" />
<link href="" rel="stylesheet" />

2. Local data example: (fiddle)

<input type="textbox" placeholder="Search Song" id="search-box" />

<script type="text/javascript">
  name: 'name',
  local: ['yasser', 'shyam', 'sujesh', 'siddhesh', 'vaibhav']


3. MVC Web Api example :

public class SongController : ApiController

    public JsonResult GetSongs(string searchTerm)
        List<Songs> songList = new List<Songs>();
        songList.Add(new Songs{ Name = "Addat", Artist = "Aatif Aslam", Year = "2007"});
        songList.Add(new Songs{ Name = "Woh Lamhey", Artist = "Jal - The band", Year = "2008"});
        songList.Add(new Songs{ Name = "Kryptonite", Artist = "3 Doors Down", Year = "2009"});
        songList.Add(new Songs{ Name = "Manja", Artist = "Amit Trivedi", Year = "2013"});
        songList.Add(new Songs{ Name = "Tum hi ho", Artist = "Arjit Singh", Year = "2013"});

        songList = songList.Where(m => m.Name.Contains(searchTerm)).ToList();

        return songList;

public class Songs
    public string Name { get; set; }
    public string Year { get; set; }
    public string Artist { get; set; }

    name: 'songs',
    valueKey: 'Name',
    remote: {
        url: '/Song/GetSongs?searchTterm=%QUERY'

Hope this helps :)

How to setup Elmah.MVC with ASP.NET MVC 4 ?

What is Elmah ? ELMAH is an open source project whose purpose is to log and report unhandled exceptions in ASP.NET web applications.

Why to use Elmah ? ELMAH serves as an unobtrusive interceptor of unhandled ASP.NET exceptions, those usually manifesting with the ASP.NET yellow screen of death.

So now we know what and why to use Elmah, Lets quickly get started on how to use Elmah with your ASP.NET MVC project.

Step 1: Right click on your solution and select the “Manage Nuget Packages” option Elmah - Step 1 - Manage Nuget Packages

Step 2: In the Nuget Package manager search for “Elmah” and install the Elmah.MVC nuget extension.Step 2 - Elmah - Elmah mvc nuget search The Nuget Package manager will download and add the required dlls and modify the web.config’s <appSetting> for Elmah to work. Step 2 - Elmah - Elmah mvc nuget web config

Step 3: That’s it !! Your Elmah is now ready to test. I have generated a 404 to test if my Elmah works, ELMAH can be accessed by this url : Elmah - Output Screen 0Elmah - Output Screen 1

Hope this helps :)

Further Reading :

ASP.NET MVC 4 Data Annotations by example.

1. Email Validation using regex

[Required(ErrorMessage = "Enter your email address.")]
[RegularExpression(@"^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$", ErrorMessage = "Email is not valid")]
public string Email { get; set; }

2. Max and Min length check

[Required(ErrorMessage = "Enter your password.")]
[StringLength(50, MinimumLength = 4, ErrorMessage = "Password has to be  between 4 to 50 characters.")]
public string Password { get; set; }

How to read all errors from ModelState in ASP.NET MVC

ModelState plays an important role in client-side validation with ASP.NET MVC. Today I wanted to validate my model on server side and prepare a list of errors based on this validation.

I was able to do this using a little LINQ,

public static List<string> GetErrorListFromModelState(ModelStateDictionary modelState)  
var query = from state in modelState.Values  
from error in state.Errors  
select error.ErrorMessage;

var errorList = query.ToList();  
return errorList;  

The above method returns a list of validation errors. Hope this helps :)

Further Reading :

How to get all Errors from mvc modelState?

How do I get the collection of Model State Errors in ASP.NET MVC?