X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Monday, February 16, 2015

Using local storage in jquery

Introduction for using local storage in jquery
Local storage is basically used to store the information at client side i.e, within user browser. Local storage can accommodate more data unlike cookies and the data is secure too.

How localstorage is better than Cookies ?
Below are the pros of localstorage -

  • localstorage is supported by modern browsers out now.
  • localstorage can store nearly 5 MB of data where as cookies can only store 4 KB
  • localstorage data has not been sent in HTTP header unlike cookies.

Above only few pros have been listed since this post is on using the localstorage in our project.

How to use localstorage in my project ?

So i will use the same list of files as i have created in my earlier post. You can find that post here.

And my javascript file has been modified to introduce localstorage. So here i am going to store the value of "Category Name" field (created in previous post) in localstorage as you see below -

$(document).ready(function () {
 $("#saveCategory").click(function () {
  
  var categoryName = $("#CategoryName").val();

  localStorage.setItem('name', categoryName);

  if($("#frmCategory").valid())
   $("#frmCategory").submit();
 }); 
});
In the above code "Category Name" field value is being stored in localstorage having key 'name'.

Now to display the value of localstorage (as alert box)  i will create a new action method as shown below and i change my post action method like this -

[HttpPost]
public ActionResult Index(Category catgr)
{
 return RedirectToAction("TestAction");
}

public ActionResult TestAction()
{
 ViewBag.Message = "Your test page.";
 return View("Test");
}
As you can see above new action method "Test Action" has been added and it is calling "Test.cshtml". So this page is just created to display the localstorage (in alert box).

So below is the code to display the value stored in localstorage -

<script type="text/javascript">

 var value = localStorage.getItem('name');

 alert(value);

 localStorage.removeItem('name');
</script>
So the above script is being added in "Test.cshtml". Make sure you remove the item added in the localstorage once its used because the value will be there till localstorage is being removed or cleared and it could cause some unexpected results.

Hope you enjoyed this article. Please put your comments below.





Saturday, February 14, 2015

Jquery validation plugin remove rules


Introduction of jquery validation plugin

This article is the continuation of my previous jquery validation plugin article Unlike my previous article "Jquery validation plugin rules" here i am trying to remove the data annotation validation dynamically from jquery validation plugin.

Approach for using jquery validation plugin rules

After solving the issues of validate method in my project (explained that issue in this jquery validation plugin post ) i have added the data annotation validations, created a models etc.

Now lets see how we can remove the validations dynamically using jquery validation plugin in my MVC project -

Lets create a new MVC Project from Web template.

First we will create a model which we are going to use across the project -

public class Category
{
 [Required]
 public int CategoryID { get; set; }
 [Required]
 public string CategoryName { get; set; }
}
As you can see in the above code snippet, "Category" model is added with properties - "CategoryID" and "CategoryName" which are required. So basically in page when the user does not enter these values then error message - "Please Enter Category ID or Please Enter Category Name" will be displayed.

Now lets create a controls for these fields -

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "frmCategory" }))

{

 <div class="row">

  <div>

   <label class="label_txt">@Html.LabelFor(m => m.CategoryID)</label>

   @Html.TextBoxFor(m => m.CategoryID)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.CategoryID)

  </div>

 </div>



 <div class="row">

  <div>

   <label class="label_txt">@Html.LabelFor(m => m.CategoryName)</label>

   @Html.TextBoxFor(m => m.CategoryName)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.CategoryName)

  </div>

 </div>



 <input type="button" class="saveCategory" value="Save" id="saveCategory" />

}

As you can see above, I am using  type="button" and not type="submit" because in the click event of the button control i will submit the form using jquery. Below is the complete code of Jquery file -

$(document).ready(function () {
 
 $("#saveCategory").click(function () {
  
  if ($("#frmCategory").valid())
   $("#frmCategory").submit();
 }); 
 
});
As you see in the above code we are just validating the form controls. As we discussed earliar, if the user has not entered the value in any of the textboxes, required error will be thrown. So after executing the above code we will get error like this in the screenshot -

Jquery validation plugin remove rules

Now we will try to remove the validation for "Category Name" field and if we enter the value in field "Category ID" the form becomes valid. Let us change the code to remove the validation for "Categoty Name" -

$(document).ready(function () {

 $("#saveCategory").click(function () {

  $("#CategoryName").rules("remove");

  if ($("#frmCategory").valid())
   $("#frmCategory").submit();
 }); 
 
});
So after adding this code validation for "Category Name" field will be disabled. See the below screenshot of the screen as how it looks when "Save" button is clicked -
Jquery validation plugin remove rules

Once enter value for "Category ID" field, the form will be valid and it submits the form and below is the screenshot of post method, which is called after form submit -

Jquery validation plugin remove rules

So null value will be passed to "Category Name" field and the entered value - 5 goes to "Category ID" field.

I hope this article has helped you guys. Please comment your thoughts below.

typeerror $(...).validate is not a function jquery


Problem
In my project i have _Layout.cshtml and Index.cshtml and my javascript files. In my javascript file i am trying to use validate() method of Jquery plugin as i want to validate the form before submit. When i run my project i was getting error –
$(…).validate is not a function
Solution 1
If you are using validate() method of Jquery plugin then we have to make sure the library – “jquery.validate.min.js”  is being added. So even after adding this library in my Index.cshtml page issue has not yet been solved.  – Still an Issue
Solution 2
Added “jquery.validate.min.js” library in my _Layout.cshtml (master page) after registering the Jquery bundles. So we have to make sure “jquery.validate.min.js” library should be added after main Jquery library. So the sequence should be like below –

jquery-1.7.1.min.js
jquery.validate.min.js
jquery.validate.unobtrusive.min.js

typeerror $(...).validate is not a function jquery
Make sure you are following the above sequence because of one library dependent on other. And make sure you have enabled the client side validation in web.config like below –

 
<appSettings>

 <add key=”webpages:Version” value=”3.0.0.0″ />

 <add key=”webpages:Enabled” value=”false” />

 <add key=”ClientValidationEnabled” value=”true” />

 <add key=”UnobtrusiveJavaScriptEnabled” value=”true” />

</appSettings>

Adding in _Layout.cshtml under <body> tag like below has solved the validate() method issue –

@Scripts.Render(“~/bundles/jquery”)
@Scripts.Render(“~/bundles/bootstrap”)
@RenderSection(“scripts”, required: false)


<script src=”~/MyFolder/jquery.validate.min.js” type=”text/javascript”/>
<script src=”~/MyFolder/jquery.validate.unobtrusive.min.js” type=”text/javascript”/>

<!-- Your other javascript libraries -->

Hope this article has solved your issue also. Please comment below.


Sunday, February 8, 2015

Jquery form submit confirm dialog

Introduction of Jquery form submit confirm dialog

Consider a scenario where we need to post the values of ASP.NET MVC Form on click of "Yes" button in confirm dialog. There are many questions raised in different forums on this topic so i thought lets discuss this today. Here i will try to explain how we can do it with easy steps. 

Approach for Jquery form submit confirm dialog

First step would be to create a class called "Customer.cs"  and using this as our model to our view.
 
public class Customer
{
 public string Fname { get; set; }
 public string Lname { get; set; }
 public string Address { get; set; }
}

Jquery form submit confirm dialog
I will use the existing "HomeController.cs" file for this example so lets change the content of "index.cshtml" view to incorporate customer model changes. Below is the sample of ASP.NET MVC Form -


@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { Id = "frmCustomer" }))
{

 <div class="row">

  <div>

   @Html.LabelFor(m => m.Fname)

   @Html.TextBoxFor(m => m.Fname)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.Fname)

  </div>

 </div>

 <div class="row">

  <div>

   @Html.LabelFor(m => m.Lname)

   @Html.TextBoxFor(m => m.Lname)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.Lname)

  </div>

 </div>

 <div class="row">

  <div>

   @Html.LabelFor(m => m.Address)

   @Html.TextBoxFor(m => m.Address)

  </div>

  <div class="error_align_left align_left_processor">

   @Html.ValidationMessageFor(m => m.Address)

  </div>

 </div>

 <div class="align_left_tabs">

  <input type="button" value="Save" name="Save" id="SaveCustomer" />

 </div>
}

As you can see in the above code snippet of ASP.NET MVC Form, properties  - "Fname", "Lname" and "Address" are all input fields. So once the user enters the data into these text boxes and clicks the "Save" button, Pop up (Confirm Dialog) will appear and it gives user a option either "Save" or "Cancel". So Pop up content will be obtained from partial view. So we are creating an action method to load the pop up. 

Below is the code snippet for these functionalities -

First is loading the partial view on click on "Save" button 
 
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script type="text/javascript">

 var WarningURL = '@Url.Action("WarningPopUp", "Home")';

 $(document).ready(function () { 

  $("#SaveCustomer").click(function () {

   showWarningPopup();

  });


  function showWarningPopup() {

   var $confirm = $("<div id='divWarning'></div>");

   $confirm.empty();

   $confirm.dialog({

    autoOpen: false,

    title: 'Message',

    width: 400,

    draggable: false,

    resizable: false,

    closeOnEscape: false,

    dialogClass: 'no-close',

    modal: true,

    height: 150,

    cache: false,

    open: function (event, ui) {

     $confirm.load(WarningURL);

    }

   });

   $confirm.dialog("open");

   return false;

  }

 });

</script>

As you can see above function - "showWarningPopup" is used to display a pop up (confirm dialog) and "WarningURL" variable is pointing to the action - "WarningPopUp", which is in "Home" controller. 

Action method -
 
public ActionResult WarningPopUp(string name)
{
 return PartialView("_WarningPopup", name);
}

Pop up/ Confirm Dialog code -


<script type="text/javascript">

 function destroyPopup() {

  $('#divWarning').dialog('destroy').remove();

 }

 function postCredentials() {

  $("#frmCustomer").submit();

 }

</script>

<div id="timeOutPopup" class="row_shift20">

 <div style="margin-bottom:50px">Please Confirm Details</div>

 <ul>

  <li class="popUpCancelBtnWidth"><input type="button" value="Cancel" onclick="destroyPopup()" /></li>

  <li class="popUpConfrmBtnWidth"><input type="button" value="Save" onclick="postCredentials();" class="green_input" /></li>

 </ul>
</div>
The above method is quite straight forward. As we discussed on click of "Save" button javascript function - "postCredentials" which submits the parent form (which has user entered values). After putting breakpoint in the post method it looked like this -

Jquery form submit confirm dialog

Hope you enjoyed this article of ASP.NET MVC Form even though it is long. Please comment your thoughts below.

Saturday, February 7, 2015

Dynamic queries in sql server


Introduction

Dynamic queries in SQL are a single set of SQL statements which could be stored in a variable and executed dynamically. There are various methods from which we can do this in SQL Server.

Now lets check how we can do this in a practical approach -

To Demonstrate this lets create a stored procedure with dynamic queries in SQL Server and then execute the stored procedure to check the results. Below is the sample stored procedure with dynamic queries in SQL Server -

/****** Object:  StoredProcedure [dbo].[SP_GetStudentDetails]    Script Date: 02/07/2015 20:47:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_GetStudentDetails]
@classID INT = 0,
@teacherID INT = 0,
@studentName VARCHAR(50) =''
AS
BEGIN

 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

 --first option
 
 DECLARE @whereclause VARCHAR(200) = ''
 DECLARE @Fullstmt VARCHAR(2000)

 --  dynamic queries in SQL Server for filtering based on Class
 IF @classID <> 0 
 BEGIN
   SET @whereclause += 'AND Class_ClassID = ' + CAST(@classID AS VARCHAR(20))
 END

-- dynamic queries in SQL Server for filtering based on teacher.
IF @teacherID <> 0 
 BEGIN
   SET @whereclause += 'AND Teacher_TeacherID = ' + CAST(@teacherID AS VARCHAR(20))
 END

 PRINT @studentName

-- dynamic queries in SQL Server for filtering based on student name.
IF @studentName <> '' 
 BEGIN
  SET @whereclause += 'AND StudentName LIKE  ''' + '%' + @studentName + '%' + ''' ' 
  
 END

 SET @Fullstmt = 
  'SELECT * FROM Students WHERE 1=1 ' + @whereclause
 
 EXECUTE(@Fullstmt) 
 
END

Dynamic queries in sql server
The above stored procedure does nothing fancy when the values are passed for the parameters - "Teacher ID", "Class ID" and "Student Name" it will filter the students based on that.
 
EXEC SP_GetStudentDetails  @studentName = 'Student1'

Finally the result will look like this -

Dynamic queries in sql server

Thanks for reading and please give comment below.