Enum Support in MVC 5.1

MVC 5.1 introduced some really great support for enums as announced in the MVC 5.1 release notes.

Given the following enumeration and model class...

public enum Heroes 
{ 
     Batman,
     Superman,
     WonderWoman
}

public class EnumSample
{
     public Heroes Hero { get; set; }
}

...using the following built in HTML helper method...

@Html.EnumDropDownListFor(m => m.Hero)

...renders a drop down with the enumeration names:

image

 

 

 

Cool! Exactly what we expected: a drop down list with the enumeration options. What if we wanted to show the enumeration names in a more friendly manner, like putting a space in WonderWoman?

Turns out, this is no problem for the new helper. The text that is displayed honors any DisplayAttributes that have been applied to the enum values.

public enum Heroes
{
     Batman,
     Superman,
     [Display(Name="Wonder Woman")]
     WonderWoman
}

public class EnumSample
{
    public Heroes Hero { get; set; }
}

Line 5 above is where the magic happens. Notice that I did not use a DisplayNameAttribute as you might have expected. The reason is that the DisplayNameAttribute is not valid for Fields and will throw a compiler error.

@Html.EnumDropDownListFor(m => m.Hero)

now renders the following:

image

 

 

 

Sweet! Now we have nice, friendly display values.

Where it breaks down

You would think that the added support for creating drop down lists and honoring display attributes would also apply to simply displaying a enumeration value

@Html.DisplayFor(m => m.Hero)

and… you would be wrong.

image

The solution

There are a few solutions available if you google it (with bing, of course!). Unfortunately, most of them are related to creating a drop down list for enum values. There are a couple of answers on stackoverflow that provide simple utility classes/methods to wrap up the reflection required to get the name from the attribute.

I was really looking for something cleaner and easily discoverable. So, I created my own HtmlHelper specifically for displaying the names of enum values.

@Html.EnumDisplayFor(m => m.Hero)

Let's take a look at the code:

public static MvcHtmlString EnumDisplayFor<TModel, TValue>(this HtmlHelper html, Expression<Func<TModel, TValue>> expression)
{
    return EnumDisplayNameFor(html, expression);
}

public static MvcHtmlString EnumDisplayNameFor<TModel, TValue>(this HtmlHelper html, Expression<Func<TModel, TValue>> expression)
{
    if (html.ViewData == null || html.ViewData.Model == null)
        return MvcHtmlString.Empty;

    var metaData = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

    if (EnumHelper.IsValidForEnumHelper(metaData))
    {
        var enumType = metaData.ModelType;
        var enumName = Enum.GetName(enumType, metaData.Model);

        var enumField = enumType.GetField(enumName, BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public);

        if (enumField != null)
        {
            var attr = enumField.GetCustomAttribute(inherit: false);

            if (attr != null)
            {
                string name = attr.GetName();

                if (!string.IsNullOrWhiteSpace(name))
                    return MvcHtmlString.Create(name);
            }
        }
    }

    return DisplayExtensions.DisplayFor(html, expression);
}

Basically, all we're doing is checking to see if the enum value in the model has a DisplayAttribute, and if so, try to grab the Name from it.

The EnumHelper.IsValidForEnumHelper method is part of the framework, and I used it here to make sure that the model value is an enum and that it does not contain flags. I'm not sure why having flags would cause an issue, but I included the check to maintain consistency with the EnumDropDownListFor method.

The DisplayExtensions.DisplayFor method was used here for consistency with the framework as well.

What about discoverability?

Adding the namespace to the web.config file did not make these extension methods available in my views. I'm not sure why. The only way I could get them to be available was to add the explicit using at the top of each view where I needed to use them. Needless to say, not very good for discoverability.

After fighting with this for some time, I ultimately decided to put these in the System.Web.Mvc.Html namespace. As dirty as it feels to do that, the nice side effect is that by simply referencing the DLL, these methods instantly become available to all of your views without having to muck with web.config or add additional namespaces to your views. The ultimate in discoverability!

In conclusion

I'm pretty satisfied with the solution that I've come up with. These extension methods are available on NuGet:

Install-Package RedWall.MVCSugar

The source, including a sample project, is available on GitHub.

No, I Don't Want a Ticket for the Women's Luncheon

Women in Technology

Perhaps one of my greatest pet peeves is the term "women in technology." The hatred of this term began for me in middle school when the school's IT director set up an elective class titled "Women in Technology." She came to me explicitly and asked me to join because I had just participated in creating the school's first website (and if you're out there, Mrs. Weber, thank you for jumpstarting my web career). I eagerly agreed that it was a perfect fit. She meant well, I'm sure, but the only memory I have of the class is a group of teenage girls, myself included, at the Rocky Mountain Chocolate Factory putting tiny sweaters on tiny stuffed bears, sipping hot cocoa, and talking about boys. What did this field trip have to do with technology, let alone women in technology?

So when I attended DevConnections in Las Vegas for the first time, it was with great hesitation that I accepted the ticket for the Women in Technology Luncheon. Meet us for lunch Wednesday afternoon, and celebrate women in technology. By Wednesday morning, my husband--also attending the conference--was cringing every time I noticed the ticket tucked in my badge holder and bracing himself for another tirade.

My initial hesitation about going to the luncheon had gradually grown into a vehement denial that the luncheon should exist in the first place. What was the point of it? Was it a support group? A private club with a "no boys allowed" sign stuck on the table? I had come to this conference to learn about exciting changes in the industry, and here I was, 15 years later, being invited to clothe teddy bears again. In reality, the luncheon was probably a pleasant gathering of intelligent women--I don't know, I couldn't bring myself to go. But to me, it was more than a luncheon: it was a giant neon sign that flashed, "Look at us. We're different."

Pride in Successful Women

Don't get me wrong. I am not ashamed of being female, and I don't agree that women should be excluded from or marginalized in an industry that is, currently, male-dominated. I admit to feeling great pride when I see successful women in the industry, such as Michele Leroux Bustamante and Julie Lerman. In fact, I loved introducing my team of developers (all male) to WCF and Entity Framework, not only because the technologies are fantastic, but also because I could point to the names on the covers of the books and say, "See? You don't need a beard or an extended forehead to be an expert."

What bothers me about "women in technology" is the apparent need to beat their bosoms and proclaim that the industry must change to accommodate them, must recognize that they exist, must treat them equally!! -- but differently.

Feminism is a Humanism

In college, I grudgingly took a class entitled "Feminist Bioethics." Great, I thought when I signed up for the class, an entire quarter on abortion. Still, it was the only bioethics class at the university, so I decided to take a chance.

I was surprised by the class, not only because of the variety of bioethical issues that were specific to women that had never occurred to me, but also because it taught me what feminism actually is--and what it is not.

Feminism is not the idea that women are better than men. Feminism is not the idea that women should be vaunted and revered. Feminism is not the idea that men should pay for millennia of misogyny and inequality. Feminism is simply the idea that, yes, men and women are different--and it doesn't matter. When it comes down to it, both men and women are human. This transcends gender, sex, roles--it is a simple and undeniable truth. The core belief of feminism--more aptly named humanism--is that anyone, male or female or otherwise, is entitled to the basic rights and privileges and respect that is due to any human.

That's it! Gender plays no part in your being human. I am proposing that gender need not play any part in your career in technology, either. As Stacey Mulcahy says, "I hope that if someone chooses to toss an adjective in front of your job title, that it is about your qualifications - not your gender." By calling yourself a "woman in technology" and hosting a special luncheon, you are putting that adjective on your job title yourself.

"I totally fucking disagree!"

Which is why it is infuriating when women in technology start imposing themselves on the industry and demand that it change to accommodate them. It is that attitude that leads Uncle Bob to admonish male developers that there are ladies present and to act accordingly. It's not Uncle Bob's fault; his heart is in the right place. He admits that he doesn't understand what the hell women in technology want. That’s because women in technology want it all: praise for standing up against adversity and no adversity. At the same time. Of the examples that Uncle Bob brings up in his article, only one woman seemed to have any sense: the one that yelled, "I totally fucking disagree."

Self-discrimination

Yes, there are some challenges with being a woman in technology. But how many of those are self-imposed or imagined? I kept my pregnancy a secret from my developers for months because I didn't want to draw attention to the fact that I am female. I didn’t want to lose any of the respect that I had worked hard for as their peer and later as their manager. Did any one of them care when I finally revealed it? Did it affect their opinions of me? Of course not. It was a ridiculous fear, just as ridiculous as the idea that men making sex jokes at a conference threatens women's place in the industry.

Professionalism

Uncle Bob makes the point that those types of jokes are unprofessional no matter who is in the room, and I do agree with that. But that's an entirely different argument altogether. It has nothing to do with women. Generic sex jokes don't hurt women any more than they hurt men. But what if the joke is directed at someone in particular?

Two of my male colleagues joked the other day that a female colleague had to have been so successful because she gave sexual favors to an industry leader, not because she had any real skill. My temper flared. This is exactly what women have to put up with! But as I thought about it later, I realized that, had they been talking about a man, I probably wouldn't have cared. But wouldn't the joke have been just as hurtful? What if they had just said that she was a brownnoser? Isn't that essentially the same thing? And the bottom line is that I also have no idea why this particular person is so successful--she doesn't appear to have the skills to match her success. For all I know, my male colleagues could have been on the right track.

And if we want to talk about professionalism, why should men have to put up with women bursting into tears at the slightest conflict? "Not all women are like that! That’s a stereotype!" Oh, but all brogrammers are misogynists?

Be proud of who you are because of what you do

Meanwhile, the most successful women in technology are respected because they are experts in their craft, not because they are loud and disruptive about issues that, at the end of the day, aren't holding any of us back in our careers. If you want a raise, then ask. If you want a promotion, then ask. If you see actual evidence of discrimination, then it is your duty to make it known. The statistics about women being underpaid and underemployed in comparison to their male counterparts are real. Those statistics have to change.

But keep in mind that intentionally labeling and setting yourself apart is directly sabotaging your goal of desensitizing the industry to the novelty of women. The most important part of who you are in your career is not your gender, so stop categorizing yourself as "women in technology." That label does nothing for your salary, it does nothing for your job title, and it does nothing to prove that you are an equal. Only your work and your passion can do that.

The beginning of something awesome

After years of false starts, we have finally started a blog. The idea is for all of us at Red Wall to contribute and keep track of the things we are doing, or going through, on a regular basis.

We will blog on a broad range of topics that we think may be valuable for world at large. or thoughts that we don’t want to lose track of.

Our intention is to provide value to the community and we invite you to take this journey with us.

History