Build a MVC RadioButtonList Helper

I want a Radio Button List for my MVC site. There is no out of box solution for it. But it is pretty easy to build your own.

        public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>( 
            this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TProperty>> expression, 
            IEnumerable<SelectListItem> listOfValues) 
        { 
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); 
            var sb = new StringBuilder();

            if (listOfValues != null) 
            { 
                // Create a radio button for each item in the list 
                foreach (SelectListItem item in listOfValues) 
                { 
                    // Generate an id to be given to the radio button field 
                    var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);

                    // Create and populate a radio button using the existing html helpers 
                    var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text)); 
                    var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();

                    // Create the html string that will be returned to the client 
                    // e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label> 
                    sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label); 
                } 
            }

            return MvcHtmlString.Create(sb.ToString()); 
        } 
    }

Build a fully customized MembershipProvider and RoleProvider

The problem:

UsreId is widely used in all kind of web applications. The question is how you can pass the userId to different location in your web application. By using Session variable? Make something like Session["UID"]=blahblahblah? Oh come on, it is 21st century already and we need something new. Session variable is a cool choice; I use it a lot before I switch to the custom MembershipProvider and the RoleProvider.

The main drawback of Session is that it can be lost due to variety reasons. Once your Session is gone, everything stored in it is gone too.

Take a quick look on this line of code.

var userName = User.Identity.Name;

Is it possible to make something like  User.Identity.UserId ?

The answer is yes, and that is why we need our CustomMembershipProvider.

Continue reading