Creating user friendly strings for C# enums

Standard

Recently one of my colleague asked me question, he want to create a enum with string values. But C# doesn’t support string based enums, so here is the code snippet which will help you to associate string values to enums. This code is not using any custom attribute, instead it is using DescriptionAttribute class. Here is the enum, with the associated string values.

enum OrderStatus
{
    [Description("New Order")]
    NewOrder = 1,
    [Description("Order is processing")]
    Processing = 2,
    [Description("Order is shipped")]
    Shipped = 3
}

And here is the extension method, which returns the string value associated to the enum

public static class Extensions
{
    public static string Description(this Enum @enum)
    {
        var description = string.Empty;
        var fields = @enum.GetType().GetFields();
        foreach (var field in fields)
        {
            var descriptionAttribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (descriptionAttribute != null && 
field.Name.Equals(@enum.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                description = descriptionAttribute.Description;
                break;
            }
        }

        return description;
    }
}

You can get the description from enum like this.

var orderStatus = OrderStatus.NewOrder;
Console.WriteLine(orderStatus.Description());

Happy Programming :)

Update : Based on the comment from NDVictory, source code modified to return the exact value, earlier it was always returning the first value. Thank you NDVictory

MVC5 Ajax form is not updating DIV but replacing the whole page instead

Standard

While working on MVC5 application, I faced this issue, I was using Ajax.BeginForm() and from controller, I was returning content result. But instead of updating the DIV, the content was opened in new Tab. Initially I thought it was due to some javascript error, but it was not working with Ajax.ActionLink also. Later I found it was due to missing “Microsoft.jQuery.Unobtrusive.Ajax” package. You can install this via NuGet.

NuGet package - Microsoft.jQuery.Unobtrusive.Ajax

NuGet package – Microsoft.jQuery.Unobtrusive.Ajax

And include it in the BundleConfig.cs.

bundles.Add(new ScriptBundle("~/bundles/jqueryunobtrusive").Include(
            "~/Scripts/jquery.unobtrusive*"));

And include the jqueryunobtrusive in _layout.cshtml file.

@Scripts.Render("~/bundles/jqueryunobtrusive")

It will resolve this issue.

Happy Programming :)

Load ASP.NET MVC partial views on link click

Standard

Some one asked me how we can load partial views on link click. Here is the snippet for the same.

Long version – Using JQuery

<script type="text/javascript">
$("#loadPartialView").click(function () {
    $.get('@Url.Action("LoadPartialView","Home")', {}, function (response) {
        $("#Display").html(response);
    });
});
</script>

And here is the small version using Ajax.ActionLink

@Ajax.ActionLink("Load Partial View", "LoadPartialView", "Home",
    new AjaxOptions() { UpdateTargetId = "Display" })

In the page, you need to add a DIV with Id attribute which got a value “Display”, partial view will be loaded to this DIV.

And here is the controller action

public ActionResult LoadPartialView()
{
    return PartialView("_PartialView");
}

Happy Programming :)

How to identify static class using reflection

Standard

Today someone asked me, how to find static class from list of types. I was against the implementation he was doing, but still I couldn’t find how to find static class. Later I did some research and I found like you need to look for IsAbstract and IsSealed properties of the type.

Here is source code, which identify the static class from the list of available types in the assembly.

class Program
{
    static void Main(string[] args)
    {
        var types = Assembly.GetExecutingAssembly().GetTypes();
        types.Where(x => x.IsAbstract && x.IsSealed).ToList()
            .ForEach(Console.WriteLine);
    }
}

static class StaticClass { }

sealed class SealedClass { }

interface Interface { }

class NormalClass { }

abstract class AbstractClass { }

If you run the above code, it will print the StaticClass name.

Happy Programming :)