Friday, 31 October 2014

Delete multiple rows using checkbox in with jquery mvc

$('#DeleteAllButtonId').click(function () {
    if ($('.chkNumber:checked').length) {
        var chkIds = "";
        $('.chkNumber:checkbox:checked').each(function () {
            chkIds += $(this).val()+",";
        });
        chkIds = chkIds.slice(0, -1).toString();
        var confirmvalue = confirm("Are you sure you want to delete selected ?");
            if (confirmvalue) {
                $.ajax({
                    url: "/Admin/DeleteMultipleBanner",
                    type: "GET",
                    data: { 'sDeleteId': chkIds },
                    success: function (data) {
                            window.location = '/Admin/Banner';
                        },
                     error: function (xhr, status, error) {
                             alert('Server Error');
                        }
                    });
                }
            }
    else {
        alert('Please Select at lease one Checkbox!');
    }                                 
});

[HttpGet]
public void DeleteMultipleBanner(string sDeleteId)
{
   
    List<int> listDeleteId = sDeleteId.Split(',').Select(int.Parse).ToList();
    // In listDeleteId you will get list of integer
    // your table name and delete query
    db.BannerMasters.Where(x => listDeleteId.Contains(x.BannerId)).ToList().ForEach(item =>     db.BannerMasters.Remove(item));
    db.SaveChanges();
}

Wednesday, 17 September 2014

Checkbox with Header in Gridview using jquery

<script type="text/ecmascript">
        $(document).ready(function () {
            $("#<%=grdBanner.ClientID%> input[id*='chkChild']:checkbox").click(function () {
                //Get number of checkboxes in list either checked or not checked
                var totalCheckboxes = $("#<%=grdBanner.ClientID%> input[id*='chkChild']:checkbox").size();
                //Get number of checked checkboxes in list
                var checkedCheckboxes = $("#<%=grdBanner.ClientID%> input[id*='chkChild']:checkbox:checked").size();
                //Check / Uncheck top checkbox if all the checked boxes in list are checked
                $("#<%=grdBanner.ClientID%> input[id*='chkAll']:checkbox").attr('checked', totalCheckboxes == checkedCheckboxes);
            });
            $("#<%=grdBanner.ClientID%> input[id*='chkAll']:checkbox").click(function () {
                //Check/uncheck all checkboxes in list according to main checkbox
                $("#<%=grdBanner.ClientID%> input[id*='chkChild']:checkbox").attr('checked', $(this).is(':checked'));
            });
        });
    </script>

<asp:TemplateField>
                            <HeaderTemplate>
                                <asp:CheckBox runat="server" ID="chkAll" />
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox runat="server" ID="chkChild" />
                            </ItemTemplate>
                        </asp:TemplateField>

Thursday, 11 September 2014

Ajax Post With Multipler Param

$('#send_btn').click(function () {
    $.ajax({
            type: "POST",
            url: "Home.aspx/InsertEnquiry",
            contentType: "application/json; charset=utf-8",
            data: "{'sName':'" + $("#<%=txtName.ClientID%>").val(); + "','sMessage':'" + $("#<%=txtName.ClientID%>").val(); + "'}",
            dataType: "json",
            success: function (data) {
                    alert(data.d);
                },
                error: function (xhr, status, error) {
                    alert("Error");
                }
            });
    });

Tuesday, 2 September 2014

Check String is Palindrom or Not

Console.Write("Enter String : ");
            string strGiven = Console.ReadLine();
            int length = strGiven.Length;

            string strTemp = string.Empty;
            for (int i = length - 1; i >= 0; i--)
            {
                strTemp += strGiven[i].ToString();
            }
            if (strTemp == strGiven)
            {
                Console.Write("Enterd {0} string is Palindrom",strGiven);
            }
            else
            {
                Console.Write("Entered {0} string is NOT Palindrom", strGiven);
            }
            Console.ReadLine();

Interview Patterns


Pattern 5

Console.Write("Enter loop repeat number(rows): ");
            int num = Convert.ToInt16(Console.ReadLine());
            for (int i = 1; i <= num; i++)
            {
                for (int j = num-i; j >= 1; j--)
                {
                    Console.Write(" ");
                }
                for (int k = 1; k <(2*i); k++)
                {
                    Console.Write("*");
                }
                Console.Write("\n");
            }
            for (int i = num-1; i >= 1; i--)
            {
                for (int j = num; j > i; j--)
                {
                    Console.Write(" ");
                }
                for (int k = 1; k < (i * 2); k++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            Console.ReadKey();

Pattern 4

Console.Write("Enter loop repeat number(rows): ");
            int num = Convert.ToInt16(Console.ReadLine());
            for (int i = num; i >= 1; i--)
            {
                for (int j = 5; j > i; j--)
                {
                    Console.Write(" ");
                }
                for (int k = 1; k < 2 * i; k++)
                {
                    Console.Write(k);
                }
                Console.WriteLine();
            }
            Console.ReadKey();

Pattern 3

Console.Write("Enter loop repeat number(rows): ");
            int num = Convert.ToInt16(Console.ReadLine());

            for (int i = 1; i <= num; i++)
            {
                for (int j = num - i; j >= 1; j--)
                {
                    Console.Write(" ");
                }
                for (int k = 1; k < (i * 2); k++)
                {
                    Console.Write(k);
                }
                Console.WriteLine();
            }
            Console.ReadKey();

Pattern 2

Console.Write("Enter loop repeat number(rows): ");
            int num = Convert.ToInt16(Console.ReadLine());
            for (int i = 1; i <= num; i++)
            {
                for (int j = num - i; j >= 1; j--)
                {
                    Console.Write(" ");
                }
                for (int k = 1; k < (i * 2); k++)
                {
                    Console.Write(k);
                }
                Console.WriteLine();
            }
            Console.ReadKey();

Pattern 1

 Console.Write("Enter loop repeat number(rows): ");
            int num = Convert.ToInt16(Console.ReadLine());
            for (int i = 1; i <= num; i++)
            {
                for (int j = num - i; j >= 1; j--)
                {
                    Console.Write(" ");
                }
                for (int k = 1; k <= i; k++)
                {
                    Console.Write(k);
                }
                Console.Write("\n");
            }
            Console.ReadKey();

Dimond

int i, j, n;
            Console.WriteLine("Enter no for printing star in diamond shape");
            n = int.Parse(Console.ReadLine());
            for (i = 1; i <= n; i++)
            {
                for (j = n; j >= i; j--)
                {
                    Console.Write(" ");
                }
                for (j = 1; j <= i; j++)
                {
                    Console.Write("*");
                }
                for (j = 1; j <= i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }


            for (i = 1; i <= n; i++)
            {
                for (j = 0; j <= i; j++)
                {
                    Console.Write(" ");
                }
                for (j = n; j >= i; j--)
                {
                    Console.Write("*");
                }
                for (j = n; j >= i; j--)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            Console.ReadKey();

Spiral Pattern

public static void Print()
        {
            Console.Write("Enter n: ");
            int n = Convert.ToInt32(Console.ReadLine());
            int[,] matrix = new int[n, n];
            int positionX = 0;
            int positionY = 0;
            int direction = 0;
            int stepsCount = n - 1;
            int stepPosition = 0;
            int stepChange = n % 2 == 0 ? n - 1 : n;

            for (int i = 1; i <= n * n; i++)
            {
                matrix[positionY, positionX] = i;
                if (stepPosition < stepsCount)
                {
                    stepPosition++;
                }
                else
                {
                    stepPosition = 1;
                    if (stepChange == 1)
                    {
                        stepsCount--;
                    }
                    stepChange = (stepChange + 1) % 2;
                    direction = (direction + 1) % 4;

                }

                switch (direction)
                {
                    case 0:
                        positionX++;
                        break;
                    case 1:
                        positionY++;
                        break;
                    case 2:
                        positionX--;
                        break;
                    case 3:
                        positionY--;
                        break;
                }
            }
            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    Console.Write("{0, 4}", matrix[row, col]);
                }
                Console.WriteLine();
            }
        }

Monday, 14 July 2014

LogIn in asp.net c# By Cookie

// Create Cookie
Response.Cookies["UserName"].Value = "value Here";
Response.Cookies["AdminId"].Value = "value Here";
Response.Redirect("ToPage");

OR  Create Cookie With Expiration Time
 HttpCookie cookie_lid = new HttpCookie("lId", "value Here");
cookie_lid.Expires = DateTime.Today.AddDays(1);
Response.Cookies.Add(cookie_lid);

// To Delete Cookie

Response.Cookies["UserName"].Expires = DateTime.MinValue;
Response.Cookies["AdminId"].Expires = DateTime.MinValue;


// Check Cookie is Exsits other wise redirect default
if (Request.Cookies["UserName"] == null ||string.IsNullOrEmpty(Request.Cookies["AdminId"].Value))
            {
                Response.Redirect("Default.aspx");
            }

Wednesday, 25 June 2014

Setting Expiry Cache On Static Content in

http://madebyseth.com/posts/2013/december/setting-expiry-cache-on-static-content-in-umbraco/

Tuesday, 24 June 2014

Check UnCheck Chekbox inside nested repeater

<script type="text/javascript">
   function toggleSelectionUsingHeaderCheckBox() {
   $("input[name$='chkMain']").each(function () {
   // get all child checkbox
   var subCheckbox = $(this).parent().parent().next().find("td").find("table").find("tr").find("td").find("input[name$='chkSub']");
      subCheckbox.prop('checked', $(this).prop('checked'));
      });
  }
 </script>

Friday, 18 April 2014

Get JSON format


using System.Web.Script.Serialization;

add refernce System.Web.Extensions

 JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(loCountry);
return sJSON;

Saturday, 22 February 2014

Press Enter and Click event fire on textbox

  txtSearch.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + lbtnSearch.UniqueID + "','')");

Tuesday, 4 February 2014

Saturday, 1 February 2014

Check Cooki Enabled In Browser

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
     // Check if the browser supports cookies
     if (Request.Browser.Cookies)
     {
             if (Request.QueryString["CheckCookie"] == null)
            {
                   // Create the test cookie object
                   HttpCookie cookie = new HttpCookie("TestCookie", "1");
                   Response.Cookies.Add(cookie);
                  // Redirect to the same webform
                 Response.Redirect("Default.aspx?CheckCookie=1");
         }
         else
         {
            //Check the existence of the test cookie
            HttpCookie cookie = Request.Cookies["TestCookie"];
            if (cookie == null)
            {
              lblMessage.Text = "We have detected that, the cookies are disabled on your browser. Please enable cookies.";
            }
         }
      }
      else
      {
        lblMessage.Text = "Browser doesn't support cookies. Please install one of the modern browser's that support cookies.";
      }
   }
}

Thursday, 30 January 2014

Caching Absolute and Sliding

Absolute Expiration: A DateTime Object that specifies when the data should be removed from the cache.Whe you specify "Absolute Expiration",the cache item will expire at that time,irrecspective of whether the acached tem is access or not.
(In Short It will be expired after given time automatically);

Sliding Expiration:A TimeSpan object that idetfies how long the data should remain in the cache after was last accessed..
(In Short It will remain in cache from the time of last accessed)

Absolute and Sliding Expiration can not be used together.

1. Using "Cache" object's Insert() method

Example : Cache.Insert("KeyName", DATAFORCACHE);

2. Using "Cache" object's Add() method

Example: Cache.Add(""KeyName"", DATAFORCACHE, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);

CacheItemPriority enum values:

1) CacheItemPriority.Low
2) CacheItemPriority.BelowNormal
3) CacheItemPriority.Normal
4) CacheItemPriority.Default
5) CacheItemPriority.AboveNormal
6) CacheItemPriority.High
7) CacheItemPriority.NotRemovable

Wednesday, 29 January 2014

Fragment Caching

Fragment Caching
Caching parts of webform is called as Partial caching or Fragment caching. In a web application development, there might be scenarios where most parts of the web page changes, but only a specific section of the page is static. Let's say that specific section also takes a long time to load. This is an ideal scenario, where fragment caching can be used.

Steps to fragment cache a webform
1. Encapsulate that sepcific sections of the page that does not constantly change into a user control.
2. Use the OutputCache directive on the user control to specify the cache settings.
3. Drag and drop the user control on the webform.

<%@ OutputCache Duration="60" VaryByParam="None" Shared="true" %>

Difference between VaryByParam and VaryByControl?

When should we use VaryByParam over VaryByControl and vice versa?
                                                   OR
What is the difference between VaryByParam and VaryByControl?
If you want to cache multiple responses of a user control, based on a query string or a form "POST" parameter, then use VaryByParam. On the other hand, if you want to cache multiple responses of a user control, based on a control value then use "VaryByControl".

Tuesday, 28 January 2014

Multiple file upload

// Add multiple= true

<asp:FileUpload ID="FileUpload1" multiple="true" runat="server" />

// c# code on upload click
if (FileUpload1.HasFile) // CHECK IF ANY FILE HAS BEEN SELECTED.
{
   int iUploadedCnt = 0;// to count files
   HttpFileCollection hfc = Request.Files;
 
   for (int i = 0; i <= hfc.Count; i++)
   {
      HttpPostedFile hpf = hfc[i];
      if (hpf.ContentLength > 0)
      {
         filename = Path.GetFileName(hpf.FileName);
         hpf.SaveAs(Server.MapPath("~/images/") + Path.GetFileName(hpf.FileName));
         iUploadedCnt += 1;
      

       }
   }
   lblMessage.Text = "<b>" + iUploadedCnt + "</b> file(s) Uploaded.";
}
else
{
  Give msg Here // lblMessage.Text ="No files selected.";
}

Saturday, 25 January 2014

Get Chechbox Bool Value With Id inside Gridview


<asp:TemplateField HeaderText="Publish">
   <ItemTemplate>
      <asp:CheckBox ID="chkStatus" runat="server" AutoPostBack="true" Checked='<%# Convert.ToBoolean(Eval("publish")) %>'
            Testid='<%# Eval("OptionId")%>' Text='<%# Eval("publish").ToString().Equals("True") ? " <img src=\"../App_Themes/CPTheme/Images/active.png\" alt=\"Yes\"/> " : " <img src=\"../App_Themes/CPTheme/Images/deactive.png\" alt=\"No\" " %>'
             OnCheckedChanged="chkStatus_CheckedChanged" />
   </ItemTemplate>
</asp:TemplateField>

protected void chkStatus_CheckedChanged(object sender, EventArgs e)
{
  CheckBox chkStatus = (CheckBox)sender;
  GridViewRow row = (GridViewRow)chkStatus.NamingContainer;
  string id = chkStatus.Attributes["Testid"];
  bool status = chkStatus.Checked;
}
 

Friday, 24 January 2014

Change SessionId By code

SessionIDManager Manager = new SessionIDManager();
string NewID = Manager.CreateSessionID(Context);
string OldID = Context.Session.SessionID;
bool redirected = false;
bool IsAdded = false;
Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded);
Response.Write("Old SessionId Is : " + OldID);
if (IsAdded){ Response.Write("<br/> New Session ID Is : " + NewID); }
else{Response.Write("<br/> Session Id did not saved : ");}

GridView Multiple Delete By Jquery toggle or Without Postback

---------------------------- Add this script in head section------------
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        function toggleSelectionUsingHeaderCheckBox() {
            $("input[name$='chkChild']").each(function () {
                if ($("input[name$='chkHeader']").prop('checked')) {
                    $("input[name$='chkChild']").prop('checked', true);
                }
                else {
                    $("input[name$='chkChild']").prop('checked', false);
                }
            });
        }
        function toggleAll() {
            $("input[name$='chkChild']").change(function () {
                if ($("input[name$='chkChild']:checked").length == $("input[name$='chkChild']").length) {
                    $("input[name$='chkHeader']").prop('checked', true);
                }
                else {
                    $("input[name$='chkHeader']").prop('checked', false);
                }
            });
        }
        $(document).ready(function () {
            $("#<%=lbwthDelete.ClientID%>").click(function () {
                var totalSelected = $("input[name$='chkChild']:checked").length;
                if (totalSelected == 0) {
                    alert('No Row Selected');
                    return false;
                }
                else
                    return confirm(totalSelected + ' row(s) will be Deleted?');
            });
        });
    </script>------Add template field in Gridview Header Checkbox and child Chekbox------------------------
<asp:TemplateField>
  <HeaderTemplate>
      <asp:CheckBox ID="chkHeader" onClick="toggleSelectionUsingHeaderCheckBox();"
runat="server" />
  </HeaderTemplate>
  <ItemTemplate>
      <asp:CheckBox ID="chkChild" onClick="toggleAll();" runat="server" />
  </ItemTemplate>
</asp:TemplateField>

-----------------------Click Event get selected checkbox value and delete it---

protected void btnDelete_Click(object sender, EventArgs e)
    {
        List<string> listofEmployeeIdtoDelete = new List<string>();
        foreach (GridViewRow a in GridView1.Rows)
        {
            if (((CheckBox)a.FindControl("chkChild")).Checked)
            {
                string EmployeeID = ((Label)a.FindControl("lblEmployeeID")).Text;
                listofEmployeeIdtoDelete.Add(EmployeeID);
            }
        }
        if (listofEmployeeIdtoDelete.Count > 0)
        {
            lblMessage.ForeColor = System.Drawing.Color.Navy;
            foreach (string strEmployeeID in listofEmployeeIdtoDelete)
            {
                EmployeeDataAccessLayer.DeleteEmployee(Convert.ToInt32(strEmployeeID));
            }
            lblMessage.Text = listofEmployeeIdtoDelete.Count.ToString() + "row(s) Delete";
        }
        else
        {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "No records selected to delete.";
        }
        bindgridview();
    }

Thursday, 23 January 2014

Capitalize Name By Code

* Include Name Space* 

using System.Threading;
using System.Globalization;


string MenuName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
    ToTitleCase(MenuName.ToLower());

C#

C#

Required Field By Code

<script type="text/javascript">
     function fnCheck() {
         if ((document.getElementById("<%=txtname.ClientID%>").value).length == 0) {
             alert("Name should not be empty!");
             return false;
         }
         else if ((document.getElementById("<%=txtEmail.ClientID%>").value).length == 0) {
             alert("Email should not be empty!");
             return false;
         }
         else if ((document.getElementById("<%=txtfeedback.ClientID%>").value).length == 0) {
             alert("Feedback should not be empty!");
             return false;
         }
         else {
             return true;
         }
     }
    </script>

<asp:Button ID="btnsubmit" runat="server" Text="SUBMIT" OnClientClick="return fnCheck();" />

Allow Only Numbers

<script type="text/javascript">
    //Function to allow only numbers to textbox
    function validate(key) {
        //getting key code of pressed key
        var keycode = (key.which) ? key.which : key.keyCode;
        var phn = document.getElementById('txtSortOrder');
        //comparing pressed keycodes
        if (!(keycode == 8 || keycode == 46) && (keycode < 48 || keycode > 57)) {
            return false;
        }
        else {
            return true;
        }
    }
    </script>

<asp:TextBox ID="txtPhn" runat="server"

onkeypress="return validate(event)"></asp:TextBox>
 

Javascript

Javascript related posts