Introduction to jquery Date Picker in ASP.NET MVC

In this article, I am going to show how to integrate jquery Date Picker with ASP.NET MVC project.

Step 1 : Import jquery.js and jquery-ui.js files

<script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.23.min.js")" type="text/javascript"></script>

Step 2 : Define a DateTime property in model

public class TaskModel
    public DateTime TaskScheduled { get; set; }

Step 3 : Declare Razor textbox for Date Time input using the model.

Note that I have defined a class called “date”, which I will be using in my jquery call and bind it to my textbox.

<div class="editor-label">Scheduled for :</div>
<div class="editor-field">@Html.TextBoxFor(m => m.TaskScheduled, new { @class = "date" })</div>

Step 4 : and finally some javascript code :)

$(document).ready(function() {</p>
    $('.date').datepicker({ dateFormat: "dd/mm/yy" });

**Ouput : and voila your date picker is ready to serve :) **

Hope you found this useful. Cheers !

How to move an item to top of list using Linq

Say I have a list of students like the one shown below, and I want a specific item to be on the top of the list.

Here in the example below I want the Student with “Top” as his FirstName to be on the top of the list. So here is how you do it.

var students = new List<Students> { 
    new Students{Id = 1, FirstName = "Yasser", LastName = "Shaikh"},
    new Students{Id = 2, FirstName = "Jayesh", LastName = "Mandal"},
    new Students{Id = 3, FirstName = "Siddhesh", LastName = "Vasani"},
    new Students{Id = 4, FirstName = "Top", LastName = "Top"},
    new Students{Id = 5, FirstName = "Roshan", LastName = "Punwani"}

Now there are two methods to do this, I’m gonna show both of them, so here goes..

Method 1:

This method does not work on Linq to Sql.

var students = students.OrderBy(m => m.FirstName != "Top").ToList();

Method 2:

This works on both Linq and Linq to Sql.

var index = students.FindIndex(x => x.FirstName == "Top");
var topItem = students[index];
students.Insert(0, topItem);

Hope you found this useful. Cheers !

How to Call Stored Procedure from Entity Framework in ASP.NET MVC

You can call Stored Procedure and Views using Entity Framework, I recently had to use one and didn’t find any good article describing this, so I am writing this one down.

Below is a Stored Procedure I have prepared for this example. As you can see in this stored procedure, there is 1 input parameter and 1 output parameter. I have tried to keep the stored proc as simple as possible :)

@username varchar(50),
SELECT * FROM dbo.Users WHERE username = @username
SET @total = (SELECT COUNT(*) FROM dbo.Users)

Now that we have defined our stored proc, let move towards our next step.

Open your .edmx file and right click on the designer and select the “Update Model From Database”

then select the new stored procedure added from the list and select “Finish”.

Now right click on the designer again, and select the “Add -> Function Import” option this time.

Select the stored procedure from the list of Stored Procedures, give a nice function name I have given mine “Test_EF” now as I have my stored proc return a value I have used Complex Type. To create a complex type simply click on the “Create a New Complex Type” and Visual Studio will create one for you. Click ok.

And so if all is ok, you should be able to see the function added to your model browser as shown in the screenshot below.

And now you can use the stored procedure like any other table call,

For example:

using(var context = new SimplePmEntities())
    var data = context.Test_EF("yasser", 0);

Hope you found this useful ! Cheers !

Sql How to clear the recent connection from the drop down in SQL Server Management Studio

The procedure to do this is pretty simple and straight forward,
1. Open SQL Server Management Studio
2. Delete or rename mru.dat or SqlStudio.bin file

To help you locate these files, check the below list.

Are you using Windows Server 2003 or Windows XP with SQL Server Management Studio 2005 ?
mru.dat is present at C:\Documents and Settings\username\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell

Are you using Windows Server 2008, Windows Vista and Windows 7 with SQL Server Management Studio 2005 ?
mru.dat is present at C:\Users\\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell

Are you using Windows Server 2008, Windows Vista and Windows 7 with SQL Server Management Studio 2008 ?
SqlStudio.bin is present at C:\Users\\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell

Find the file, delete/rename it and now when you open your Sql Server Managment studio all the saved recent connections, username and password will be cleared.

Hope this helps you :)

Sql Script to implement Server side Paging and Sorting

I myself, am not much of an SQL guy, so when I was asked up to write a stored procedure to handle server side sorting and paging, I was pretty skeptical about it.

So here is what I came up with, Hope this help you too.

I have 4 input fields to it. These fields are as follows
1. sort_order : to pass wether the order is “Ascending” or “Descending”.
2. sort_column : Here I pass the column name using which the table will be sorted.
3. page_number : Used to specify the current page number and
4. page_size : Is used to specify the amount of rows allowed per page.

also I have setup some logic to skip and take rows depending upon which page the user is on and the page size

@rows_to_skip = (@page_number – 1) * @page_size

Below is the full SQL script.

USE [my-db]

ALTER PROCEDURE [dbo].[SP_Get_Records]
	@record_id  INT,
	@sort_order varchar(50),
	@sort_column varchar(50),
	@page_number INT = 1,
	@page_size INT = 5,

	DECLARE @rows_to_skip INT	
	SET @rows_to_skip = (@page_number - 1) * @page_size
		CASE WHEN @sort_column = 'first_name' AND @sort_order = 'asc' 	THEN dbo.Users.FirstName END ASC,
		CASE WHEN @sort_column = 'first_name' AND @sort_order = 'desc' THEN dbo.Users.FirstName END DESC,
		CASE WHEN @sort_column = 'last_name' AND @sort_order = 'asc' 	THEN dbo.Users.LastName END ASC,
		CASE WHEN @sort_column = 'last_name' AND @sort_order = 'desc' THEN dbo.Users.LastName END DESC,

		CASE WHEN @sort_column = 'NULL' AND @sort_order = 'asc' THEN dbo.Users.FirstName END ASC)
		FROM dbo.Users 
		WHERE record_id = @record_id
	) p
	WHERE row_no >= @rows_to_skip + 1
	and row_no <= @rows_to_skip + @page_size


$(this) is not working in success method of ajax

I recently came to know that the $(this) does not work in the success/error method of ajax.

I was trying to remove a div on success of some ajax call, and it just didn’t work. But when I tried using jsFiddle suprising it worked, below is the jsfiddle.

Jsfiddle Link :

So I posted this as a question on Stackoverflow.

And the answer was pretty simple, use the context:this property.

Example :

$('.doneBtn').live('click', function () {
    var taskId = $(this).attr(&quot;data-taskid&quot;);

        url: '/Task/TaskCompleted/?strTaskId=' + taskId,
        type: &quot;POST&quot;,
        context: this,
        success: function (data) {
        error: function (xhr, ajaxOptions, thrownError) {


Using Return Url in ASP.NET MVC 3

Implementing returnUrl in ASP.NET MVC is easy and pretty straight forward. Below are the steps you need to follow to ensure that it works correctly.

Step 1 : Setup the loginUrl to the appropriate action. In my example I have set it to “LogOn” action of the Account Controller.

<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />

Step 2 : Setting up controller,

public ActionResult LogOn(string returnUrl)
	return View();

public ActionResult LogOn(LogOnModel model, string returnUrl)
	if (ModelState.IsValid)
		if (ValidateUser(model.UserName, model.Password))
			return SignIn(model, returnUrl);
			ModelState.AddModelError("", "The user name or password provided is incorrect.");
	return View(model);

private ActionResult SignIn(LogOnModel model, string returnUrl)

	if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
		return Redirect(returnUrl);
		return RedirectToAction("Index", "Home");

Step 3 : Posting the return Url from the form to the Logon Controller.

@using (Html.BeginForm("LogOn","Account",new { returnurl = Request.QueryString["returnurl"] })) {

Hope this helps :)

Introduction to DropDownList with ASP.NET MVC 3 Razor

Drop downs are a part of any web application. And in ASP.NET MVC 3, drop down lists are preapred by using @Html.DropDownListFor() method.

I always keep on forgetting on how to

  1. Populate a dropdown list
  2. Read the selected value back into the controller,

So I have decided to write this as an article which would help me save time in future and this could also serve as a reference article to those who are new to DropDownList in MVC.

Lets start..

At the controller side, you need to have a List of SelectListItem type. I have passed this list to my ViewBag.DropDownData, here you could have passed it to your model instead, but I am trying to keep it as simple as possible. So you pass the list to a viewbag.

Controller code

var myList = new List<SelectListItem>
new SelectListItem {Text = "Yasser", Value = "YS"},
new SelectListItem {Text = "Vaibhav", Value = "VS"},
new SelectListItem {Text = "Ramanjit", Value = "RS"}

ViewBag.DropDownData = myList;

Now in the view using the @Html.DropDownListFor() method, the first argument should be a string/int (depending upon your value) declared in your model which will be later be used when data is posted back to the controller. The second parameter is the List we just prepared, in case if you are using a model then simply pass your model here instead.

Razor View

@Html.DropDownListFor(m => m.ValueSelected, ViewBag.DropDownData as List<SelectListItem>)

There that’s it. Your dropdown is ready to go :), here’s the ouput of my code:


Some other ways

ASP.NET MVC 3 Dropdownlist of Users