Friday, April 4, 2014

Default if Empty...

In this tutorial, will go over using DefaultIfEmpty() in Linq to Objects to handle values when none found.

For this example, I created a sample windows application and wrote the following line of code to test.

In the above code, I had declared a List of type string without adding any values. When I try to access the first value, it is going to throw exception and say none found. Before handling them with try / catch there is another way to add one more step of validation before accessing it.


Above image captures an exception thrown when accessing data in an empty object. In this scenario, there is always an option to use a default value, when no items found. For example, see the image below...

To handle this situation, I had introduced the option to provide Empty string as substitute when list contains no items. Now, when I run the sample code, the output message box will be....


Here, the messagebox displays the default value i.e. empty string. Now lets add some values and try to run the same.


In the above scenario, I added two values to the list item and invoking it will give me the result as User1 (first item in the list). Also, you can use any string value to replace empty string to validate null situations.

Happy coding...

Wednesday, April 2, 2014

Loading jQuery on demand...

There might be situations, where we need to navigate to a new View / Page which does not be part of _layout.cshtml (that is the place where the common includes go). It might help there to check if jQuery is loaded and if not, then it can be included on that page on demand.

An example that worked for me is,

<script type="text/javascript">

    if (typeof jQuery == 'undefined') {
        document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></' + 'script>');
    }

</script>

I got this reference from a website (which I don't remember), but there are many interesting flavors to it available on the web....

Happy coding....