Archives

Archives / 2014
  • Validate Model Programmatically in ASP.NET MVC

    ASP.NET model binding framework takes care of validating a model based on data annotation validations. This works well when a model is being bound with request data. However, at times you may need to create and fill a model programmatically. In such cases, although the model properties are decorated with data annotation validators, they won't validate the data because they are not invoked at all. Luckily, ASP.NET MVC allows you to validate a model object via code. This article shows how.

  • Utilize HTML5 DataList and jQuery Ajax to Create Autocomplete in ASP.NET MVC

    In data entry forms involving textboxes with predictable values one can use autocomplete to assist user pick an existing value. HTML5 introduces datalist element that can come handy while implementing autocomplete. The datalist element holds a list of options and can be attached with a textbox using list attribute. By adding a bit of jQuery Ajax you can dynamically populate the options in a datalist. This article shows you how to do just that.

  • Use XMLHttpRequest to Call ASP.NET Web API

    Most of the times developers use jQuery $.ajax() to call ASP.NET Web API from the client side script. At times, however, you may need to plain JavaScript to invoke the Web API. Luckily, calling a Web API using XMLHttpRequest object and plain JavaScript is not too difficult. This article discusses how that can be done with a sample Customer Web API.

  • Customize HTML5 Validation Messages in ASP.NET MVC

    HTML5 allows you to put constraints on the data entered in form fields through several techniques. These techniques include new input types (such as email and url) and attribute such as required and pattern. When these constraints are violated the browser shows an error message callout and the form submission is cancelled. Although this default arrangement works great in many applications, at times you may want to customize the error messages and how they are displayed. This article explains how such a customization can be achieved with the help of a couple of new events and a dash of jQuery code.

  • Utilize HTML5 ContentEditable in ASP.NET MVC to Edit View Content

    Usually ASP.NET MVC developers create two separate views for displaying data in read-only and editable form. Although this technique works well, you can utilize a feature of HTML5 to conveniently read as well as edit data on the same view. HTML5 offers contenteditable attribute that magically turns any read-only area of a web page into an editable region. Using contenteditable in combination with some jQuery code you can easily develop a view that toggles between read-only and editable mode.

  • Receiving Data As FormDataCollection in ASP.NET Web API

    The Web API actions must follow prescribed signatures in order to work as expected. More often than not this parameter is of a complex type that wraps the actual pieces of data in its properties. This arrangement goes well when you know the exact model being passed by a client. However, this arrangement is of no use when a client is sending arbitrary pieces of data not mapping to any model. Luckily, Web API provides a way to deal with such data. This article discusses just that.

  • Customize View, Partial View and Layout Search Locations in ASP.NET MVC

    By default ASP.NET MVC stores all the views associated to a controller inside a sub-folder of Views folder. On the same lines partial views and layout pages are stored inside Shared sub-folder under Views folder. Although this default arrangement works well in most of the cases, at times you may want to deviate from this convention based arrangement and store views, partial views and layouts in some different folder structure. Luckily, you can easily deal with the situation by creating a custom view engine. This article tells you how.

  • Load ASP.NET MVC Partial Views Dynamically Using jQuery

    Most of the times ASP.NET MVC views are rendered as a result of user navigating to some action. For example, when a user navigates to /home/index in the browser (either through address bar or through a hyperlink), ASP.NET MVC executes the action method and usually returns a view to the browser. This means each view is rendered as a result of a full GET or POST request. At times, however, you may want to load views dynamically through Ajax. This way you can render contents of a view without full page refresh.

  • Perform List, Insert, Update and Delete in a Single View in ASP.NET MVC

    A common way to perform list, insert, update and delete operations in ASP.NET MVC is to create four separate views. The List view forms the launching view where records are displayed and you can choose to Edit, Delete or Insert a record. However, in some cases you may want to perform all these operations in a single view itself. This task can be accomplished using full page postback or using Ajax. This article discusses the former technique.

  • Optimize ASP.NET MVC Views with Bundling and Minification Features

    ASP.NET MVC web applications often use client side scripting in one or the other way. Use of JavaScript libraries such as jQuery and frameworks such as AngularJS is quite common these days. Therefore it is important to pay attention to the rendering of the views. Especially, script load time is worth some consideration. Luckily, ASP.NET MVC offers help in the form of bundling and minification features. This article shows how these features can help you optimize the views.

  • Understanding JavaScript Prototypes (and creating your own "$" library)

    Many web applications developed today use some or the other JavaScript library or framework. These libraries and frameworks heavily rely on what is known as JavaScript prototypes. Therefore, it would be interesting to any web developer to understand this concept. This short article explains in brief what JavaScript prototypes are and how they form an integral part of many of the popular JavaScript libraries. You also learn to create your own "$" library.

  • Implementing Sorting and Paging in Web API using OData queries

    The client displaying data returned by a Web API may want to implement sorting or paging on the data being returned. Although there can be different ways to implement these features, a simple technique is to use OData support offered by the Web API. This article shows how to call a Web API by using a client-side script and also shows how to implement Ajax-driven sorting and paging.

  • Implementing Sorting and Paging in ASP.NET MVC

    Displaying records in a table is a very common requirement in many web applications. Such a table also needs facilities such as sorting the data based on a specific column and pagination for the sake of easy navigation and display. Unlike ASP.NET web forms, MVC doesn't have readymade server controls such as GridView to ease your job. One needs to either use a third-party helper or make some custom provision to accomplish this task. This article shows how persistent and bidirectional sorting as well as paging can be implemented in ASP.NET MVC without any external dependencies.

  • Display image from byte array in ASP.NET MVC

    Displaying images from wellknown URLs is quite straightforward. At times, however, you need to display images that are available as raw binary data. Consider, for example, that you are building a Captcha system that generates images on the fly. These images won't reside on the server as physical files. They will be generated and held in memory using System.Drawing classes (or something similar). To display them you can't point the src attribute of an <img> element to a particular URL as such.

  • Learn ASP.NET MVC, jQuery, AngularJS & HTML5 in Thane. Registration started for November 2014 batches!

    We will be conducting a 5 day intensive training programs on ASP.NET MVC, jQuery, AngularJS and HTML5 in the month of November 2014. Small batches, personal attention and real world examples. Registration has already started. In case you or your friends are interested to join please get in touch with us as soon as possible. The courses are conducted in Thane. You may read more details here.

  • Securing ASP.NET MVC Applications with ASP.NET Identity

    ASP.NET offers Forms Authentication as one of the authentication schemes. Developers often use Forms Authentication in combination with membership, roles and profile features to provide security to their web applications. Over the years the needs of authentication schemes used in a web application have changed. To take into account these changing trends Microsoft has released ASP.NET Identity - a new way to authenticate users of your web application. This article describes how ASP.NET Identity can be used in an ASP.NET MVC application from the ground up.

  • Using Display Templates and Editor Templates in ASP.NET MVC

    ASP.NET MVC developers often use HTML helpers such as LabelFor() and TextBoxFor() to display model properties on a view. Although this approach works fine in many situations, it proves to be inadequate when you wish to customize how data is presented to the user for displaying and for editing. Luckily, you can use display templates and editor templates to overcome this limitation. This article discusses what display templates and editor templates are and how to use them in an ASP.NET MVC application.

  • Learn ASP.NET MVC in Thane. Registration started for October 2014 batches !

    We will be conducting a 5 day intensive training program on ASP.NET MVC in the month of October 2014. Learn MVC5, EF6, Web API 2, VS2013 and more. Small batches, personal attention and real world examples. Registration has already started. In case you or your friends are interested to join please get in touch with us as soon as possible. The courses are conducted in Thane. You may read more details here.

  • Wrapping multiple calls to SaveChanges() in a single transaction

    When you make any additions, modifications and deletions to an Entity Framework DbSet and call SaveChanges(), EF starts a new transaction and executes all the INSERT, UPDATE and DELETE operations inside that newly created transaction. If the call to SaveChanges() succeeds the underlying transaction is committed, otherwise the transaction is rolled back. In some cases you may want that multiple calls to SaveChanges() be executed in the same transaction. Luckily, Entity Framework 6 provides an easy way to accomplish the same.

  • Self-Hosting an ASP.NET Web API

    ASP.NET Web API can be either be hosted in IIS or in a separate host process. The former approach is usually appropriate when the Web API is part of a web application and one or more web applications are going to consume it. The later approach is suitable when you wish to avoid the overhead of hosting the Web API in IIS and want to have something lightweight. Hosting a Web API inside IIS is quite straightforward as the process is identical to hosting a web application. On the other hand, hosting a Web API in it's own process requires the creation of a host application and is referred as self-hosting. This article shows in step-by-step manner how to self-host a Web API and how to consume it using a client application.

  • What to do when SaveChanges() fails?

    Beginners often ask this question - "What course of action should I take when a call to SaveChanges() fails?" The answer may vary based on a given situation and requirement. This article discusses one way to deal with the errors and shows how to display descriptive error messages to the end user and then rollback the changes made to the model.

  • Passing data from one controller to another in ASP.NET MVC

    At times you need to pass data from an action method belonging to one controller to an action method belonging to another controller. There are three ways to accomplish this task. They are - Pass data as query string, pass data in TempData, and pass data as route parameters. Let's quickly see how each of these three approaches work.

  • Overview of OWIN and Katana

    As OWIN is becoming popular and more common, it is important for ASP.NET developers to understand what OWIN and Katana are. ASP.NET Web API and ASP.NET Identity are already geared towards using these specifications. To that end this article explains what OWIN and Katana are and how they fit into the whole web development picture for ASP.NET developers. You will also develop a simple application to get a code level understanding of these features.

  • Creating Your Own "TempBag" in ASP.NET MVC

    Some time back during one of my training programs I was asked this question by a beginner in ASP.NET MVC - "Can we have TempBag wrapper for TempData just as we have ViewBag for ViewData?" Whether such a wrapper is needed is not is a different question but if you wish you can create one using dynamic objects of C# language. Here I am going to show a quick way to wrap TempData into our own TempBag and then using it in the controller and view.

  • Video : How to Organize Your ASP.NET MVC Solution in Visual Studio?

    A lot of beginners ask this question - How should I organize my MVC projects? There is no fixed answer to this question because a lot of things depend on the size and complexity of the system being developed. However, beginners need a starting point from where they can take it forward. To that end, this video shows one possible organization of various parts of an MVC application. Remember that my aim is to present a simple and structured organization that can easily be extended or modified as per requirement.

  • Working with Cookies in Web API and HttpClient

    ASP.NET applications often use cookies to store user specific pieces of information. Not just web forms and MVC applications, Web API too can use cookies. Sometimes developers device an authentication scheme revolving around cookie as an authentication ticket. Although this article won't show you how to develop such a scheme, it illustrates how cookies can be issued and used in Web API. Specifically you will learn: How to set cookies from a Web API controller and read those cookies in a client application and how to set cookies from a client application (HttpClient) and read those cookies in a Web API controller.

  • Learn ASP.NET MVC5, EF6, Web API 2, VS 2013 in Thane

    I will be conducting a 5 day intensive training program on ASP.NET MVC in the month of July 2014. Learn VS2013, MVC5, EF6, Web API 2 and more. Small batches, personal attention and real world examples. Registration has already started. In case you or your friends are interested to join please get in touch with us as soon as possible.

  • Understanding Dependency Injection

    If you ever developed ASP.NET MVC applications you probably have come across this term - Dependency Injection. Dependency Injection is a way to implement the Dependency Inversion Principle. Simply put, Dependency Injection is a design pattern that helps a class separate the logic of creating dependent objects. The result of this separation is a loosely coupled system where there is no rigid dependency between two concrete implementations. This article discusses what Dependency Injection is and illustrates its use in an ASP.NET MVC application.

  • Dealing with Multiple Instances of Partial Views and Model Binding in ASP.NET MVC

    ASP.NET model binding is quite powerful and flexible. It caters to most of the scenarios without much configuration from developers. However, at times you may need to intervene in order to achieve the desired model binding effect. One such situation is when you use multiple instance of a partial page on a view. This article shows one possible approach to deal with such situations.

  • Writing C# Code Using SOLID Principles

    Most of the modern programming languages including C# support objected oriented programming. Features such as encapsulation, inheritance, overloading and polymorphism are code level features. Using these features is just one part of the story. Equally important is to apply some object oriented design principles while writing your C# code. SOLID principles is a set of five such principles--namely Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle and Dependency Inversion Principle. Applying these time proven principles make your code structured, neat and easy to maintain. This article discusses SOLID principles and also illustrates how they can be applied to your C# code.

  • Cascading DropDownLists using "Eager Loading" on client side

    One of my earlier articles shows how to create cascading DropDownLists by making Ajax calls to the MVC action methods. While that approach is quite common and popular recently a reader asked whether something similar can be done without making any Ajax calls. If you want to implement cascading dropdownlists purely on client side then you will need to "eagerly load" all the data needed by them at the time of loading the page. This data can be stored in a hidden field and used as and when needed. Obviously this technique is not suitable for huge amount of data since everything is loaded at once on the client side. However, if the data is small and you understand the implications of loading it in advance here is how you can accomplish the task.

  • 10 Things to Keep in Mind while Developing a New ASP.NET Web Forms Application

    Many developers are opting for ASP.NET MVC for their new web applications. However, this may not be always possible (reasons can be many and valid in a given context) and you might be required to use Web Forms for your new projects. In such cases novice developers have this doubt - "If I develop my project using Web Forms and later want to migrate to MVC, how difficult this task would be?". There is no single answer to this question. However, if you follow certain guidelines while developing a Web Forms project today, at later stage migrating to MVC would be less painful than otherwise. Here I have listed my top 10 recommendations in dealing with such a situation.

  • Overview of Design Patterns for Beginners

    Modern software development needs to address complex business requirements. It also needs to take into account factors such as future extensibility and maintainability. A good design of a software system is vital to accomplish these goals. Design patterns play an important role in such systems. While learning a programming language beginners often focus on language syntax and usage techniques. However, it is also important to understand the basics of good software design. To that end this article gives a quick understanding of design patterns. It discusses what design patterns are, their benefits and classification.

  • Creating Asynchronous Actions in ASP.NET MVC

    Asynchronous actions allow you to handle more concurrent requests and can be implemented using async / await keywords. Asynchronous actions are useful in situations where you are performing some network operation such as calling a remote service. This article discusses asynchronous actions and also shows how to create them in an ASP.NET MVC.

  • Problem setting the default value for ASP.NET MVC DropDownList

    Recently one of the readers reported a problem that the DropDownList helper is not working as expected. The problem was resolved by slightly tweaking the code but since it sounded like a tricky thing that many beginners would stumble upon I am writing this post. Let's see what the problem is, its cause and finally the little tweak that I mentioned earlier.

  • Using LinkedIn JavaScript API for User Authentication and Profile Retrieval

    Integrating third-party sign-in with a website is quite common these days. Just like Facebook and Twitter, LinkedIn too allows you to ingrate LinkedIn authentication with your own website. One simple way to achieve such an integration is to use LinkedIn JavaScript API. Using this API you can authenticate a user with their LinkedIn credentials and also retrieve their profile and connection information. Once retrieved you can use that information to integrate LinkedIn authentication with your website's security and membership framework.

  • One Time Event Handlers using jQuery and ASP.NET

    Most of the times the JavaScript event handlers attached with an element fire every time the event under consideration is raised. For example, if you wire a click event handler to the click event of a button then clicking that button will invoke the event handler function every time. At times, however, this behavior is undesirable. You can unsubscribe the click event handler when it gets executed the first time. That means you need to create event handlers that fire only one time. Luckily, jQuery provides an inbuilt way to accomplish this task - one() method.

  • Using Attribute Routing in ASP.NET MVC

    ASP.NET MVC maps a URL to an action method through what is known as Routing. By default an ASP.NET MVC URL includes a controller and an action name where the request finally lands. However, you can customize many aspects of a route such as root prefix and route parameters. ASP.NET MVC 5 allows you to define routes through certain attributes. This attribute routing is simpler and more intuitive than the older technique of defining routes because a route definition is closer to the controller and its action method. This article discusses how attribute routing can be used with examples.

  • Performing Asynchronous Operations Using Entity Framework

    Asynchronous programming involves executing operations in the background so that the main thread can continue its own operations. This way the main thread can keep the user interface responsive while the background thread is processing the task at hand. .NET framework introduced the async and await keywords that simplify asynchronous programming. Entity Framework 6.0 also supports asynchronous operations for querying and saving of the data. This article discusses the basics of using asynchronous operations of Entity Framework in desktop as well as web applications.

  • Handling Errors in ASP.NET MVC Applications

    No matter how proficiently you developed your application there are chances that your code may not work as expected and will generate an error at runtime. Users may enter some invalid data, mathematical calculations can go wrong, some network level fault may cause errors and more. That is why it is always a good idea to implement a robust error handling mechanism in your web application. To that end ASP.NET MVC offers several techniques that help you build such an error handling mechanism. This article discusses them with examples.

  • Introduction to Bootstrap

    With the increasing popularity of mobile devices, web developers are required to think about their website design for mobile devices from the beginning of a development project. Developing web applications targeting multiple devices can be challenging. Web developers often resort to third-party frameworks for features such as theming, widgets and responsive design. One such handy, popular and open source framework is Bootstrap. Using Bootstrap you can develop responsive websites without bothering too much about CSS. It provides a rich CSS framework that you can customize if the need arises. Adding common web page elements such as navigation menus, buttons, form elements and typography is quite easy with Bootstrap. This article is intended to give you a basic understanding of Bootstrap so that you can start using it in your web applications.

  • Back to Basics : Working with Debug Windows in Visual Studio

    Debugging is an important skill that every developer needs to acquire. .NET developers have a powerful debugger of Visual Studio at their disposal. Visual Studio offers many windows that can be used during the debugging session. Knowing these windows is essential for efficient debugging. To that end this article discusses some of the most commonly used debug windows of Visual Studio.

  • Introduction to CSS3 Media Queries

    With the increasing popularity of mobile devices, web developers are required to ensure that their website renders well on different devices. One important aspect in such a rendering is applying different CSS rules to different requesting devices. To that end CSS3 media queries allow you to apply CSS rules depending on the media type and its capabilities. This article examines what CSS3 media queries are and how to use them in your web pages.

  • Implementing Ajax Login in ASP.NET MVC

    Implementing Ajax based login involves many of the same steps as the normal forms authentication. However, the login page doesn't send user ID and password to the server through a standard form submission. Instead, user credentials are sent to the server via an Ajax request. The credentials are then validated on the server and the result of the verification process is conveyed to the client. If the login attempt was successful, the user is taken to the secured area of the website.

  • Model Binding to List of Objects in ASP.NET MVC

    Showing a single record for editing is quite common and the default model binding of ASP.NET MVC takes care of mapping the form fields to the model properties. However, sometimes you need to edit multiple records. For example, you may want to display an editable grid to the end user filled with existing data. The user can edit the values from multiple rows and hit Save in an attempt to save the data. In this case multiple model objects are being submitted to the action method. The single record editing works on the assumption that form field names from the view match the corresponding model property names. However, when multiple model objects are submitted this assumption is no longer valid. Luckily, by tweaking the form field names you can get this to work as expected.

  • Back to Basics : Understanding .NET Attributes

    .NET assemblies are said to be self-describing. That means the information about an assembly is stored in the assembly itself. This information is called Metadata. Moreover, .NET allows you to put additional information in the metadata through Attributes. Attributes are used in many places within the .NET framework. Some examples of attributes are [WebMethod], [ServiceContract], and several data annotation attributes such as [Required] and [StringLength]. This article discusses what attributes are, how to use inbuilt attributes and how to create custom attributes.

  • Working with Facebook SDK for JavaScript

    Now-a-days many websites provide Facebook integration to enhance the user experience. Features such as Facebook authentication, displaying Like or comments widgets, posting something on a user's wall are parts of this integration. The Facebook SDK for JavaScript provides functionality that can be consumed from the client side script to leverage such an integration. To that end this article shows you how to implement Facebook authentication, how to retrieve a user's details, such as user name and profile picture, and also illustrates how to post on the user's wall.

  • 5 CSS3 Features That Simplify Your Web Page Styling

    If you are a professional web developer chances are you use CSS for styling your web pages. The latest version of CSS - version 3 - adds many features to the CSS2 feature set, making it appealing to any web developer. This article discusses five features of CSS3 that you will find interesting. The features discussed in this article include - New selectors, border images, gradient, setting opacity and multicolumn layouts.

  • Learning, Unlearning and ASP.NET

    Software industry is one of the most dynamic industries to work with. Everyday something new comes up and you have no option but to learn it to be in the race. While learning is a commonly acquired skill by software developers, not many can acquire the unlearning abilities. My experience of training software developers tells me that this skill - unlearning - can dramatically affect your experience with a technology or tool you are learning.

  • Working with Stored Procedures in Entity Framework - Part 1

    By default entity framework generates SELECT, INSERT, UPDATE, DELETE queries to perform the respective operations on the database. At times, however, you may want to deviate from this default behavior and use stored procedures for these operations. Additionally, you may want to call arbitrary stored procedures to perform some task at hand. To that end this two part article explains how stored procedures can be dealt with in Entity Framework.

  • Creating a Slide Show Using the History API and jQuery

    During Ajax communication, page content is often modified in some way or another. Since Ajax requests are sent through a client side script, the browser address bar remains unchanged even if the page content is being changed. Although this behavior doesn't create any problem for an application's functionality, it has pitfalls of its own. That's where History API comes to your rescue. History API allows you to programmatically change the URL being shown in the browser's address bar. This article demonstrates how History API can be used with an example of a slide show.

  • 7 Things You Need To Know About Web Workers

    Web Workers allow you to run JavaScript code in the background without blocking the web page user interface. Web workers can improve the overall performance of a web page and also enhance the user experience. Web workers come in two flavors - dedicated web workers and shared web workers. This article discusses seven key aspects of web workers that you need to know if you decide to use them in your applications.

  • Posting GridView Data to MVC Controller

    Visual Studio 2013 provides a unified development environment for ASP.NET Web Forms and ASP.NET MVC applications. This unified environment is called as One ASP.NET. What it means for developers is that a single project can use Web Forms, MVC controllers and Web API. Under One ASP.NET at times the existing Web Forms may want to send and receive data to and from the MVC controllers. This article illustrates how this task can be accomplished.

  • 7 Things You Should Know About the Geolocation API

    Many websites don't need to know anything about the geographical location of their visitors. In certain cases, however, this knowledge can be useful and can be used to enhance the user experience. This knowledge can also be used to integrate special features into your application. Consider, for example, a company selling some electrical equipment. By knowing the user's geographical location you can suggest the nearest store where they can visit, and purchase the products. To provide such suggestions it is important to capture the user's location. To that end, the Geolocation API allows you to do just that. This article examines seven key things you should know about the Geolocation API in order to use it in your web applications.

  • Using Complex Types in Entity Framework

    A database table represents your application data in row-column format. Although in many cases this row-column structure can be mapped directly to entities, at times you may need to reorganize the same. Consider, for example, the Customers table of Northwind database. The Customers table has Address, City, Region, Country and PostalCode columns representing the address of the company. The entity that represents this table might not be as "flat" as the table. For example, you may wish to have a property - Location - that is of class type and has properties such as Street, City, Region and PostalCode. Luckily, entity framework allows you to do so quite easily. The remainder of this article explains how.

  • Understanding the Proper Way to Lay Out a Page with HTML5

    A web page being rendered in the browser consists of many things - logo, informative text, pictures, hyperlinks, navigational structure and more. HTML5offers a set of markup elements that allow you to create a structured layout for web pages. These elements are often termed as Semantic Markup because they convey their meaning and purpose clearly to the developer and to the browser. This article discusses some of the important HTML5 elements that can contribute to the layout of a web page.

  • Executing Raw SQL Queries using Entity Framework

    While working with Entity Framework developers mostly use LINQ to Entities to query database. However, at times you may need to execute raw queries against the database. A common scenario is when you wish to generate an SQL query dynamically. Luckily, EF allows you to execute raw queries easily. This article explains how that can be done.