Telerik Mvc Grid Extension Method to highlight grid row

Telerik Mvc Grid Extension Method to highlight InActive record

I was recently working on a project where in there was a requirement that all those grid rows which are inactive in database should be highlighted with a different colour. In this project we were working with Telerik Mvc extensions.

I googled for this, and most of the responses were like, to add a client side RowDataBound event to each of the grid & place the logic there.

According to me this is a bit of time consuming tasks. So after some research & a bit help from telerik MVC forums, I created my own extension method to highlight the grid row for which the column value of the IsActive column is false.

In our database, each of the table contains a column “IsActive” which stores a Boolean value “true” or “false” so as to represent the particular record is Active or not. A record with false value in “IsActive” column indicates that the record is InActive.

Here are some simple steps to achieve this.

  1. First we need to write an extension method which will add a handler to highlight the record. Here is the code snippet for that

2. Add following class to CSS

3. Add following javascript function to your master page

4. Append your grid like this

And that’s all we need to do the row will be highlighted like this

You can find the source code here

Upgrade Application from Asp.Net MVC2 to MVC3

Upgrade Application from Asp.Net MVC2 to MVC3

It’s been a much long after MVC3 is been released & now it is much stable. So while working on a project, I need to upgrade my ASP.Net MVC 2 project to MVC 3.

ASP.Net MVC 3 can be installed side by side ASP.Net MVC 2 on you PC, which gives you flexibility in choosing when to upgrade an MVC2 application to MVC3. It is been very easy to upgrade the project to MVC3. We just need to follow following steps

  • Remove all references of System.Web.Mvc from each project in solution.
  • Now add a reference for System.Web.Mvc 3.0 to each of the project in the solution.
  • Also add a reference of System.Web.Helpers 2.0 to web project.
  • Also add a reference of System.Web.WebPages 2.0 to web project.
  • Go to views folder & open the Web.Config file & replace Version = 2.0.0.0 with version 3.0.0.0
  • Also add following code  to this Web.Config

  • Open the root Web.Config file & replace all references of “System.Web.Mvc 2.0.0.0” with “System.Web.Mvc 3.0.0.0”.
  • Now in appSettings add following keys

  • Now we need to make sure our system.web->pages->namespaces tag contains following entries

  • In the system.web->compilation->assemblies we should have following entries

  • Finally under the configuration -> runtime section put following code

  • And lastly add following javascript on your master pages, you need to add this javascript file to Scripts folder.  We need to get this file from any asp.net mvc3 project & paste it in the scripts folder. Also it is recommended you replace the old javascript files such as MicrosoftAjax.js, MicrosoftMvcAjax.js & MicrosoftMvcValidation.js.

Yuhu……………! Here we are. Now just compile & run your code. Now it will run on MVC3. Also we need to make sure we are targeting .net Framework 4.0 while upgrading the MVC2 application to MVC3.

Also there is a tool available to upgrade the MVC2 to MVC3. Here is a link to the tool

http://weblogs.asp.net/leftslipper/archive/2010/07/28/migrating-asp-net-mvc-2-applications-to-asp-net-mvc-3-preview-1.aspx

Cheers…..!

You can find the source code here.

ASP.Net MVC & Multiple Submit Button

ASP.Net MVC & Multiple Submit Button

While developing any web applications we use to design lot more forms. Most of the times a form perform a single action, posting data to some controller. There is no necessity that each of the form will contain only a single submit button. Sometimes, we may need a form which will contain multiple submit buttons.  As in the following case

So in this case, our form will be posting data to a single action Post but it contains 2 different submit button.  So to handle this scenario, we need to code something like this in our controller.

Also this looks very simple when we have a simple Action, think how about doing this on a form of 10 fields & 4 buttons.

How if I am able to specify the name of the button near the action method wherein I will specify the name of the button on which that action needs to be invoked.  We can achieve this in Asp.Net MVC by using the ActionMethodSelectorAttribute attribute. Here is a code snippet to show the use of the attribute

The ActionMethodSelectorAttribute is executed before the Action is executed, so we here we can check which button is clicked while submitting the form using the Form NameValueCollection object on the IsValidForRequest event of the ActionMethodSelectorAttribute.

Here is the implementation code for the class.

This attribute will also help preventing the JavaScript attacks as this will only accept the values submitted by the specific submit button.

You can download the source code here.

Getting Started With ASP.Net MVC 4

This is my first post about ASP.Net MVC 4. I will be providing some links for ASP.Net MVC 4 which includes information about downloading & installing ASP.Net MVC 4.
ASP.NET MVC 4 NuGet Packages
One good news is that MVC 4 is also available via NuGet. To install MVC 4 via NuGet, type following in the Package Manager Console.

For more detail regarding NuGet package please visit http://www.nuget.org/List/Packages/AspNetMvc

ASP.NET MVC 4 for Visual Studio 2010
If you are using Visual Studio 2010 then you can use MVC 4 with Visual Studio 2010. To install MVC 4 via Web Platform Installer for Visual Studio 2010 please visit following link.
http://www.microsoft.com/web/gallery/install.aspx?appid=MVC4VS2010&prerelease=true

ASP.NET MVC 4 for Visual Studio 11 Developer Preview
If you are using Visual Studio 11 Developer Preview then you can install MVC 4 in Visual Studio 11 Developer Preview via following link.
http://www.microsoft.com/web/gallery/install.aspx?appid=MVC4VS11&prerelease=true

ASP.NET MVC 4 Direct Download Link
For Visual Studio 2010, first you need to install Visual Studio 2010 SP1 KB983509 viahttp://download.microsoft.com/download/2/3/0/230C4F4A-2D3C-4D3B-B991-2A9133904E35/VS10sp1-KB983509.exe

MVC 4 Direct link for Visual Studio 2010 http://download.microsoft.com/download/E/D/7/ED7CB028-2CBD-4E26-87D5-C9164A0B4849/AspNetMVC4VisualStudio2010Setup.exe

MVC 4 Direct link for Visual Studio 11 Developer Previewhttp://download.microsoft.com/download/E/D/7/ED7CB028-2CBD-4E26-87D5-C9164A0B4849/AspNetMVC4VisualStudio11Setup.exe

Here are some useful links about MVC4

ViewModels in ASP.Net MVC

The MVC architecture is all about separating the various layers of the applications in some logical parts. But this separation enforces some of the constraints on developers such as how to pass data from Controller to View. There are various ways to send those data to View such as using ViewData, ViewBag or TempData, the other ways is passing this data through ViewModels.

The view models group one or more entities or properties into one logical object which can be consumed by Views in order to render the contents on the View. The purpose of the View Models is to group all the necessary information required to render a view at a single place. This enforces a clear separation of Concerns, putting the data manipulation & domain entities away from the Controller & View. Using view models helps to create a good & maintainable code. Along with maintainable code, View Models are very beneficial in following cases

  1. Group all drop down related entities at a single place
  2. Master details records
  3. Pagination
  4. Dashboard details
  5. CRUD operations in which forms involves lot more controls

Although, from the above discussion it seems to be a more complex concept what View Model is, but actually it’s not. A view model is a simple C#/ VB.Net class, which contains some properties; those may involve primitive data type properties, or an entity or a set of entity.

Let’s create a ViewModel for following screen

The screen contains a text box for Name field & a drop down list for State. So ideally View Model should contain 2 properties 1 for Name & other for text box. So while rendering a view the ViewModel should be

This class will serve as a view Model when the view is rendered. So the controller will contain following code to render this form.

The above code will return a new form with State drop down list filled with 1 value NY. If we look at the AccountRegistrationGetViewModel carefully, you may notice [Required] attribute. This is one of the Data Annotations attribute supported by ASP.Net. They help us to validate the input data.

Now let’s create a view

It will generate a View which will contain following markup

But after validations user should be able to view the errors also we should accept these values at the Action Methods into a ViewModel. So let’s design that ViewModel.

So now when data is posted to the server in a Controller, we should catch this data in AccountRegistrationPostViewModel  . Also In order to show errors we need to add a property, as follows.

So our controller method will be So if validations are exploited these will be shown to user as below.

                 This is how we can use ViewModels. Initially it may look complex to create separate view Model for each function but later when it come to maintain the code, you will find it very very easy to fix the changes rather than striking you head on hardcoded strings.

You can find the source here.

Why not to use ViewData, ViewBag or TempData !

There are various ways of passing data from Controller to View or vice versa. For example when passing some values to View we can use ViewData Or TempData Or ViewBag. We set the appropriate values for keys in one of these & we can access it on view where ever we need it. This approach is used very extensively in some books as well as many of the blog posts. Though it is very easy & handy to set the values in ViewData, it has some pitfalls.

Before, we will see how we can pass the values from Controller to ViewData. Consider following simple example which contains a drop down list & a date time which we need to display on View. For that purpose controller would look something like this

[HandleError]

public class HomeController : Controller

{

private ICountryRepository _countryRepository { get; set; }

public HomeController(ICountryRepository CountryRepository)

{

_countryRepository = CountryRepository;

}

public ActionResult Index()

{

ViewData[“Country”] = _countryRepository.GetCountryList();

ViewData[“CurrentDate”] = DateTime.Now;

return View();

}

}

Here in Home controller we are setting the values for 2 entities one is Country & other is CurrentDate. Country is a drop down list whereas CurrentDate will display the current date time. The GetCountryList() function here returns IEnumerable.

The view for above will be like this

<%@ Page Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>

Home Page

</asp:Content>

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

Country : <%: Html.DropDownList(“Country”, ViewData[“Country”] as SelectList) %>

Current DateTime : <%: ViewData[“CurrentDate”]%>

</asp:Content>

Though this looks pretty simple, however we are doing a lot of hardcoded string passing which is not at all good. The main pain with passing hardcoded strings is they can never be cause on compile time. Passing hardcoded string is not a big problem, we can solve it by using string Constants. But ideally, string hardcode should be avoided in order to avoid future mess which may occur during the maintenance phase of the project. Also we need to consider situations where we may need to show more than 10 items on the view, are we going to keep all these items to ViewData ? Also, see how we need to cast ViewData[“Country”]  to SelectList in order to pass it to the DropDownList helper function. While using ViewData all across the application, we need to take this pain.

Though this post was all about not using ViewData, ViewBag or TempData, there are situations where we need to use these as we cannot use View Models there. We will discuss these things in later posts.

Advantages of ASP.Net MVC

Since its release there is been constant debate among the Microsoft Community about Web Forms Vs ASP.Net MVC. Many people think eventually ASP.Net MVC will replace the traditional Web Forms. Basically ASP.Net MVC is another approach for Web Development with ASP.Net rather than a replacement to the traditional Web Forms. However, the fact is that both of them provide a different approach for web development. They are not here to replace each other, instead they will co-exist. While developing any project or applications you just need to make the right choice.

I will not jump into ASP.Net MVC Vs Web Forms. Instead, we will discuss about ASP.Net MVC advantages.

Following are some advantages of building applications using ASP.Net MVC.

  1. It makes it easier to manage the applications by dividing an application into Models, Views & Controllers.
  2. Support for Test Driven Development (TDD).
  3. It provides more control & extensibility over the page life cycle and provides the ability to substitute several key features of the framework. This was not at all available in ASP.Net Web Forms.
  4. It is an extremely extensible & pluggable framework where in the components can be customized or replaced as per need. This allows us to have better control over the framework.
  5. ASP.Net MVC uses REST (Representational State Transfer) based URL, which makes it SEO (Search Engine Friendly).
  6. There is no concept of ViewtState in ASP.Net MVC, which used to add a lot more JavaScript to the page making the final Html fat.
  7. Good support for existing ASP.Net MVC features. It lets us to use existing ASP.Net MVC features such as Forms and Windows Authentication, URL Routing, ASP.Net membership & roles, caching, session & state management, etc.
  8. Tight control over Html mark up. ASP.Net MVC provides a clean and standard compliant mark-up. Its build in helper methods generates standard output. It encourages you to create simple mark up with CSS.
  9. Open source. Unlike the other versions of ASP.Net, ASP.Net MVC is open source. This means you are free to download the original source code & compile it by customizing the source as per our needs.
  10. Since there are no Events, Post Backs & View States in ASP.Net MVC, it truly implements the stateless nature of the HTTP.