MVC Controller Handle the browser catche

Methid1

[OutputCacheAttribute(VaryByParam = “*”, Duration = 0, NoStore = true)] // will disable caching for Index only

 

Method2

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace Iris.ClientProvisioning.Web.Filters

{

       publicclassNoCacheAttribute : ActionFilterAttribute

       {

              publicoverridevoid OnResultExecuting(ResultExecutingContext filterContext)

              {

                     try

                     {

                           filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));

                           filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);

                            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

                            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                           filterContext.HttpContext.Response.Cache.SetNoStore();

                     }

                     catch (Exception ex)

                     {

                           System.Diagnostics.Trace.WriteLine(String.Format(“No Cache Attribute: {0}”, ex.Message));

                           throw;

                     }

                     base.OnResultExecuting(filterContext);

              }

       }

}

 

Methid3

<metacharset=”utf-8″/>

    <metaname=”viewport”content=”width=device-width, initial-scale=1.0″>

    <metahttp-equiv=”X-UA-Compatible”content=”IE=edge”/>

    <metahttp-equiv=”cache-control”content=”max-age=0″/>

    <metahttp-equiv=”cache-control”content=”no-cache”/>

    <metahttp-equiv=”expires”content=”0″/>

    <metahttp-equiv=”expires”content=”Tue, 01 Jan 1990 12:00:00 GMT”/>

 

Methid4

<system.webServer>

    <modules>

      <removename=”FormsAuthenticationModule” />

    </modules>

    <httpProtocol>

      <customHeaders>

        <addname=”Cache-Control”value=”no-cache” />

        <addname=”Pragma”value=”no-cache” />

        <addname=”Expires”value=”-1″ />

      </customHeaders>

    </httpProtocol>

7 jQuery Code Snippets every web developer must have

JQuery extensively simplified web developer’s life and has become a leader in javascript available libraries. There are a lot of useful jQuery snippets available but here in this post I am going to share 7 basic and widely used code snippets that every front-end web developer must have. Even for those who are new to jQuery can easily understand and get benefit from these routinely used code snippets.

 

1. Print Page Option

Providing option to print a page is a common task for web developers. Following is the available code:

 

<!– jQuery: Print Page –>

$(‘a.printPage’).click(function(){

 

window.print();

 

return false;

});

 

<!– HTML: Print Page –>

<div>

<a class=”printPage” href=”#”>Print</a>

</div>

 

 

2. Helping Input Field/Swap Input Field

In order to make an Input Text field helpful, we normally display some default text inside it (For Example “Company Name”) and when user click on it, text disappears and user can enter the value for it.

You can try it yourself by using the following code snippet.

 

<!– jQuery: Helping Input Field –>

$(‘input[type=text]’).focus(function(){

var $this = $(this);

var title = $this.attr(‘title’);

if($this.val() == title)

{

$this.val(”);

}

}).blur(function() {

var $this = $(this);

var title = $this.attr(‘title’);

if($this.val() == ”)

{

$this.val(title);

}

});

 

<!– HTML: Swap Input Field –>

<div>

<input type=”text”

name=”searchCompanyName”

value=”Company Name”

title=”Company Name” />

</div>

 

 

3. Select/Deselect All options

Selecting or Deselecting all available checkbox options using a link on HTML page is common task.

 

<!– jQuery: Select/Deselect All –>

$(‘.SelectAll’).live(‘click’, function(){ $(this).closest(‘.divAll’).find(‘input[type=checkbox]’).attr(‘checked’, true); return false; }); $(‘.DeselectAll’).live(‘click’, function(){ $(this).closest(‘.divAll’).find(‘input[type=checkbox]’).attr(‘checked’, false); return false; });

 

<!– HTML: Select/Deselect All –>

<div class=”divAll”> <a href=”#” class=”SelectAll”>Select All</a>&nbsp; <a href=”#” class=”DeselectAll”>Deselect All</a> <br /> <input type=”checkbox” id=”Lahore” /><label for=”Lahore”>Lahore</label> <input type=”checkbox” id=”Karachi” /><label for=”Karachi”>Karachi</label> <input type=”checkbox” id=”Islamabad” /><label for=”Islamabad”>Islamabad</label> </div>

 

 

 

4. Disabling Right Click

For web developers, its common to disable right click on certain pages so following code will do the job.

 

 

<!– jQuery: Disabling Right Click –>

$(document).bind(“contextmenu”,function(e){

e.preventDefault();

 

});

 

 

 

 

5. Identify which key is pressed.

Sometimes, we need to validate the input value on a textbox. For example, for “First Name” we might need to avoid numeric values. So, we need to identify which key is pressed and then perform the action accordingly.

<!– jQuery: Which key is Pressed. –>

$(‘#txtFirstName’).keypress(function(event){

alert(event.keyCode);

});

 

 

<!– HTML: Which key is Pressed. –>

<asp:TextBox ID=”txtFirstName” runat=”server”></asp:TextBox>

 

 

 

 

6. Validating an email.

Validating an email address is very common task on HTML form.

 

<!– jQuery: Validating an email. –>

$(‘#txtEmail’).blur(function(e) {

var sEmail = $(‘#txtEmail’).val();

if ($.trim(sEmail).length == 0) {

alert(‘Please enter valid email address’);

e.preventDefault();

}

var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]

{2,4}|[0-9]{1,3})(\]?)$/;

if (filter.test(sEmail)) {

alert(‘Valid Email’);

}

else {

alert(‘Invalid Email’);

e.preventDefault();

}

});

 

<!– HTML: Validating an email–>

<asp:TextBox id=”txtEmail” runat=”server” />

 

 

7. Limiting MaxLength for TextArea

Lastly, it usual to put a textarea on a form and validate maximum number of characters on it.

 

<!– jQuery: Limiting MaLength for TextArea –>

var MaxLength = 500;

$(‘#txtDescription’).keypress(function(e)

{

if ($(this).val().length >= MaxLength) {

e.preventDefault();}

});

 

<!– HTML: Limiting MaLength for TextArea–>

<asp:TextBox ID=”txtDescription” runat=”server”

TextMode=”MultiLine” Columns=”50″ Rows=”5″></asp:TextBox>

 

 

This is my selection of jQuery code snippets but jQuery is a very powerful client-side framework and a lot more can be done using it.

Types of Constructors

Types of Constructors

 

Basically constructors are 5 types those are

 

      1.    Default Constructor

      2.    Parameterized Constructor

      3.    Copy Constructor

      4.    Static Constructor

      5.    Private Constructor

 

Default Constructor

 

A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below

 

 

using System;

namespace ConsoleApplication3

{

class Sample

{

public string param1, param2;

public Sample()     // Default Constructor

{

param1 = “Welcome”;

param2 = “Aspdotnet-Suresh”;

}

}

class Program

{

static void Main(string[] args)

{

Sample obj=new Sample();   // Once object of class created automatically constructor will be called

Console.WriteLine(obj.param1);

Console.WriteLine(obj.param2);

Console.ReadLine();

}

}

}

When we run above program it will show output like as shown below

 

Output

 

 

Welcome

Aspdotnet-Suresh

 

Parameterized Constructors

 

A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below

 

 

using System;

namespace ConsoleApplication3

{

class Sample

{

public string param1, param2;

public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters

{

param1 = x;

param2 = y;

}

}

class Program

{

static void Main(string[] args)

{

Sample obj=new Sample(“Welcome”,“Aspdotnet-Suresh”);   // Parameterized Constructor Called

Console.WriteLine(obj.param1 +” to “+ obj.param2);

Console.ReadLine();

}

}

}

When we run above program it will show output like as shown below

 

Output

 

 

Welcome to Aspdotnet-Suresh

 

Constructor Overloading

 

In c# we can overload constructor by creating another constructor with same method name and different parameters like as shown below

 

 

using System;

namespace ConsoleApplication3

{

class Sample

{

public string param1, param2;

 

public Sample()     // Default Constructor

{

param1 = “Hi”;

param2 = “I am Default Constructor”;

}

public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters

{

param1 = x;

param2 = y;

}

}

class Program

{

static void Main(string[] args)

{

Sample obj = new Sample();   // Default Constructor will Called

Sample obj1=new Sample(“Welcome”,“Aspdotnet-Suresh”);   // Parameterized Constructor will Called

Console.WriteLine(obj.param1 + “, “+obj.param2);

Console.WriteLine(obj1.param1 +” to “ + obj1.param2);

Console.ReadLine();

}

}

When we run above program it will show output like as shown below

 

Output

 

 

Hi, I am Default Constructor

Welcome to Aspdotnet-Suresh

 

Copy Constructor

 

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for this

 

 

using System;

namespace ConsoleApplication3

{

class Sample

{

public string param1, param2;

public Sample(string x, string y)

{

param1 = x;

param2 = y;

}

public Sample(Sample obj)     // Copy Constructor

{

param1 = obj.param1;

param2 = obj.param2;

}

}

class Program

{

static void Main(string[] args)

{

Sample obj = new Sample(“Welcome”“Aspdotnet-Suresh”);  // Create instance to class Sample

Sample obj1=new Sample(obj); // Here obj details will copied to obj1

Console.WriteLine(obj1.param1 +” to “ + obj1.param2);

Console.ReadLine();

}

}

}

When we run above program it will show output like as shown below

 

Output

 

 

Welcome to Aspdotnet-Suresh

 

Static Constructor

 

When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

 

 

using System;

namespace ConsoleApplication3

{

class Sample

{

public string param1, param2;

static Sample()

{

Console.WriteLine(“Static Constructor”);

}

public Sample()

{

param1 = “Sample”;

param2 = “Instance Constructor”;

}

}

class Program

{

static void Main(string[] args)

{

// Here Both Static and instance constructors are invoked for first instance

Sample obj=new Sample();

Console.WriteLine(obj.param1 + ” “ + obj.param2);

// Here only instance constructor will be invoked

Sample obj1 = new Sample();

Console.WriteLine(obj1.param1 +” “ + obj1.param2);

Console.ReadLine();

}

}

}

When we run above program we will get output like as shown below

 

Output

 

 

Static Constructor

Sample Instance Constructor

Sample Instance Constructor

Importance points of static constructor

 

      Static constructor will not accept any parameters because it is automatically called by CLR.

      Static constructor will not have any access modifiers.

      Static constructor will execute automatically whenever we create first instance of class

      Only one static constructor will allowed.

Private Constructor

 

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.

 

 

using System;

namespace ConsoleApplication3

{

public class Sample

{

public string param1, param2;

public Sample(string a,string b)

{

param1 = a;

param2 = b;

}

private Sample()  // Private Constructor Declaration

{

Console.WriteLine(“Private Constructor with no prameters”);

}

}

class Program

{

static void Main(string[] args)

{

// Here we don’t have chance to create instace for private constructor

Sample obj = new Sample(“Welcome”,“to Aspdotnet-Suresh”);

Console.WriteLine(obj.param1 +” “ + obj.param2);

Console.ReadLine();

}

}

}

 

Output

 

 

Welcome to Aspdotnet-Suresh


 

In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.

 

 

// it will works fine

Sample obj = new Sample(“Welcome”,“to Aspdotnet-Suresh”);

// it will not work because of inaccessability

Sample obj=new Sample();

Important points of private constructor

 

      One use of private construct is when we have only static member.

      Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.

      If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor

Multiple column dropdown list using Kendo inMVC4.0

<td>


<div
id
=”grid”
style=”width:100px;“></div>


</td>


<td>


<div
id
=”dropdown”
></div>


</td>

 

 

 

_Columns1 = [

{ field: “FNYR_NAME”, title: “Name” },

{ field: “FNYR_CODE”, title: “Code”}

];

 

var _lstFinyeardata = @Html.Raw(


Json.Encode(

((IEnumerable<Dhanush.FAS.BusinessEntities.FAS_FINYEAR>)ViewBag.FinYears).Select(user => new

{

FNYR_ID = user.FNYR_ID,

FNYR_CODE = user.FNYR_CODE,

FNYR_NAME = user.FNYR_NAME

})

)

);

 

 

var _dropdown = null;


var _grid = null;


debugger;

_dropdown = $(“#dropdown”).kendoDropDownList({

dataSource: [{ FNYR_CODE: “”, FNYR_ID: “” }],

dataTextField: “FNYR_CODE”,

dataValueField: “FNYR_ID”,

open: function (e) {


// If the grid is not visible, then make it visible.


if (!$(_grid.element).hasClass(“k-custom-visible”)) {

$(_grid.element).slideToggle(‘fast’, function() {

_dropdown.close();

$(_grid.element).addClass(“k-custom-visible”);

});

}

}

}).data(“kendoDropDownList”);


var $dropdownRootElem = $(_dropdown.element).closest(“span.k-dropdown”);

 


debugger;

 

_grid = $(“#grid”).kendoGrid({

dataSource: {

data: _lstFinyeardata

},

 

 

scrollable: true,

selectable: true,

sortable: true,

filterable: false,

pageable: true,

columns: _Columns1,

change: function (e) {

setTimeout(function() {


var tr = $(_grid.element).find(“tr.k-state-selected”);

 


if (tr.length > 0 && tr.hasClass(“k-grid-edit-row”) === false) {


// Get the selected row.


var fasyear = _grid.dataItem(tr);


// Display the text for the selected row in the dropdownlist.

$dropdownRootElem.find(“span.k-input”).text(fasyear.FNYR_CODE);

 

$(_grid.element).slideToggle(‘fast’, function() {

$(_grid.element).removeClass(“k-custom-visible”);

});

}

},50);

}

}).data(“kendoGrid”);

 

 

 


// Hide the grid.

$(_grid.element).css({ “border”:“1px solid grey”, “display”: “none”, “position”: “absolute”,“z-index”:“10” });

 


// Position the grid so that it is below the dropdown.

$(_grid.element).css({ “top”: $dropdownRootElem.position().top + $dropdownRootElem.height(), “left”: $dropdownRootElem.position().left });

 

$(document).click(function(e) {


// Ignore clicks on the grid.


if ($(e.target).closest(“div.k-grid”).length == 0 && $(e.target).closest(“.k-grid-edit”).length == 0 && $(e.target).closest(“.k-grid-edit-row”).length == 0) {


// If visible, then close the grid.


if ($(_grid.element).hasClass(“k-custom-visible”)) {

$(_grid.element).slideToggle(‘fast’, function() {

$(_grid.element).removeClass(“k-custom-visible”);

});

}

}

});

 

 

Class Object

[Serializable]


public
class
FASGrid

{


public FASGrid();

 


public
string FNYP_CODE { get; set; }


public
int FNYP_ID { get; set; }


public
string FNYP_NAME { get; set; }


public
string FNYP_STATUS { get; set; }

}

 

Json Object


var jsonValue = “[“ +


“{FNYP_ID:1,’FNYP_CODE’:’pPrefix1′,’FNYP_NAME’:’pPrefix1′, ‘FNYP_STATUS’:’Open’},” +


“{FNYP_ID:2,’FNYP_CODE’:’pPrefix1′,’FNYP_NAME’:’pPrefix1′, ‘FNYP_STATUS’:’Open’},” +


“]”;

 

hdnpStatus.val(jsonValue);

 

 

Converted Json to class object

List<FASGrid> fasGrid = JsonConvert.DeserializeObject<List<FASGrid>>(form.GetValue(“hdnPStatus”).AttemptedValue.ToString());

To Get the parent id of Kendo grid

// Anchor Click Event

_grdTemplates.delegate(“tbody>tr > td >a.lnk”, “click”, function (e) {

e.preventDefault();

_buttons.hide();

enableControls(false);

Get(_grdTemplates.data(“kendoGrid”).dataItem($(this).parent().parent()).TML_ID);

});

Convert viewbag IEnumerable to json object

Drop Down list mvc

 

Static

.Controller

 

 


List<SelectListItem> items2 = new
List<SelectListItem>();

items2.Add(new
SelectListItem { Text = “Days”, Value = “0” });

items2.Add(new
SelectListItem { Text = “Weeks”, Value = “1” });

items2.Add(new
SelectListItem { Text = “Months”, Value = “2” });

items2.Add(new
SelectListItem { Text = “Years”, Value = “3” });

 


var status = new
SelectList(items2, “Value”, “Text”);

ViewData[“DurationUnitList”] = status;

 

View

@Html.DropDownList(“DurationUnit”, ViewData[“DurationUnitList”] as
SelectList, new { @class = “speedA” })

 

Dynamic from Database

Controller

public
IList<Business.Department> GetDropDownValues(int iEntityID)

{


VeritySession objVeritySession = (VeritySession)Session[“VeritySession”];


using (RepositoryBase repository = new
RepositoryBase())

{


IList<Business.Department> lstSalutation = repository.ListByColumnFillter<Verity.UMS.BusinessEntities.Department>(“CompanyWBS”, Convert.ToInt32(objVeritySession.InstitutionID));

lstSalutation = (from s in lstSalutation where s.LookupTypeId == iEntityID select s).ToList<Verity.UMS.BusinessEntities.Department>();

lstSalutation.Insert(0, new Business.Department { Name = “<< Select >>”, LookupId = “0” });


return lstSalutation;

}

 

}

View

ViewData[“Salutation”] = GetDropDownValues(3);

 

 

@Html.DropDownList(“ComponentId”, new
SelectList(ViewBag.FeeComponents as System.Collections.IEnumerable, “ComponentId”, “Name”, “”), new { @class = “speedA” })

 

 

 

$(“#NoOfFeeTerms”).keydown(NumaricAllow);


function NumaricAllow() {


var key_code = window.event.keyCode;


var oElement = window.event.srcElement;


if (!window.event.shiftKey && !window.event.ctrlKey && !window.event.altKey) {


if ((key_code > 47 && key_code < 58) || (key_code > 95 && key_code < 106)) {


if (key_code > 95) key_code -= (95 – 47);

oElement.value = oElement.value;

}


else
if (key_code == 8) {

oElement.value = oElement.value;

}


else
if (key_code != 9)

{ event.returnValue = false; }

}


else

{ event.returnValue = false; }

}

 

 

 

 

Convert viewbag IEnumerable to json object

 

 

$(‘#FNYR_ID’).change(function () {

 


var fnyr_id = $(this).get(0).selectedIndex;

 

 


var array =
@Html.Raw(


Json.Encode(

((IEnumerable<Dhanush.FAS.BusinessEntities.FAS_FINYEAR>)ViewBag.FinYears).Select(user => new

{

fnyr_id = user.FNYR_ID,

fnyr_code = user.FNYR_CODE,

fnyr_name = user.FNYR_NAME

})

)

);

$(‘#FNYP_FNYR_NAME’).val(array[fnyr_id ].fnyr_name);

});