Tuesday, April 5, 2016

Upload File In MVC

Add the file tag in the view.

@using(Html.BeginForm("SaveFile", "Employee", null, FormMethod.Post, new { enctype="multipart/form-data" }))
{
<input type="file" name="file" required />
<input type="submit" value="Submit" />
}

EmployeeController

[HttpPost]
public class SaveFile()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Employee/Images/"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index", "Employee");
}

DropDownList In MVC

This post will explain you the different ways of binding the dropdownlist in ASP.NET MVC razor view engine.

Bind DropDownList with the static values.


@Html.DropDownList("Role", new List<SelectListItem>(){new SelectListItem(){ Text= "Admin", Value = "1"},new SelectListItem(){ Text= "Guest", Value = "2"},}, "Please Select", new { @class = "form-control" })

Bind DropDownList with ViewData/ViewBag values.

In controller index method the List<SelectListItem> are added and assigned to ViewBag.
public ActionResult Index()
{
List<SelectListItem> roles = new List<SelectListItem>();
roles.Add(new SelectListItem { Text = "Admin", Value = "1" });
roles.Add(new SelectListItem { Text = "Guest", Value = "2" });
ViewBag.Role = roles;
return View();
}
You can render the dropdownlist as below. Dropdownlist helper will have many overloading methods with different parameters.
@Html.DropDownList("Role", null, "All", new { @class = "control-label" })
OR
@Html.DropDownList("Role")

Friday, February 27, 2015

Server Side Validation of CheckboxList in ASP.NET & C#

We can Validate CheckboxList using the CustomValidator on Client side and server-side as well.

Our approach here will be validating the checkboxlist on server-side.

1. Add the CheckboxList with some items as below.

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
          <asp:ListItem>A</asp:ListItem>
          <asp:ListItem>B</asp:ListItem>
          <asp:ListItem>C</asp:ListItem>
 </asp:CheckBoxList>

2. Add a CustomValidator Control from the toolbox.

I have added a OnServerValidate event which will validate the checkboxlist on server side on button click.


            <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select alteast one option"  OnServerValidate="CustomValidator1_ServerValidate" ></asp:CustomValidator>


3. Add a Button to Check the Validations are working.

 <asp:Button ID="Button1" runat="server" Text="Button" />

4. the c# code for validating the list.

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            int count = 0;
            foreach (ListItem item in CheckBoxList1.Items)
            {
                if (item.Selected)
                {
                    count++;
                    break;
                }
            }

            if (count > 0)
                args.IsValid = true;
            else
                args.IsValid = false;

        }

Validate CheckboxList in ASP.NET on Client Side using Javascript

We can Validate CheckboxList using the CustomValidator on Client side and server-side as well.

Our approach here will be validating the checkboxlist on client-side.

1. Add the CheckboxList with some items as below.

<asp:CheckBoxList ID="CheckBoxList1" runat="server">
          <asp:ListItem>A</asp:ListItem>
          <asp:ListItem>B</asp:ListItem>
          <asp:ListItem>C</asp:ListItem>
 </asp:CheckBoxList>

2. Add a CustomValidator Control from the toolbox.

I have added a ClientValidateFunction which will be a javascript function ValidateCheckBoxList  to validate.

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select alt-east one option" ClientValidationFunction="ValidateCheckBoxList"></asp:CustomValidator>

3. Add a Button to Check the Validations are working.


 <asp:Button ID="Button1" runat="server" Text="Button" />


4. Add the following java script to the Page which will validate the CheckBoxList.

  <script type="text/javascript">
        function ValidateCheckBoxList(source, args) {
            var chkListModules = document.getElementById('<%= CheckBoxList1.ClientID %>');
            var chkListinputs = chkListModules.getElementsByTagName("input");
            for (var i = 0; i < chkListinputs.length; i++) {
                if (chkListinputs[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }


    </script>

GridView Export To Word ASP.NET & C#

In this article we will see how to export grid-view to excel or word.

Step 1 : Create a new database in SQL server or if you have a database already go to step 2.

CREATE DATABASE (YOUR DATABASE NAME);

Step 2 : Create a table in the database.

CREATE TABLE Employee
(
    EmployeeID INT,
    Name Varchar(250),
    Salary Decimal (10,2)

);

Step 3 : Insert some sample data to the table.

INSERT INTO Employee VALUES (1,'Scott',1000);
INSERT INTO Employee VALUES (2,'John',1100);
INSERT INTO Employee VALUES (3,'Phil',1200);
INSERT INTO Employee VALUES (4,'Peter',1300);
INSERT INTO Employee VALUES (5,'Jose',1400);

INSERT INTO Employee VALUES (6,'Morgan',1500);


Step 4 : Now Add a WebForm to your Project and add the GridView Control and Button to Export the Data.


 <asp:GridView ID="GridView1" runat="server"></asp:GridView>
 <asp:Button ID="btnExportWord" runat="server" Text="Export To Word" OnClick="btnExportWord_Click" />

Step 5 : Add the following code to your Page.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
            string connectionString = "Data Source=.SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM Employee";
                cmd.Connection = con;
                con.Open();

                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);

                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        private void ExportGridView(string fileName, string contentType)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            Response.Charset = "";
            Response.ContentType = contentType;

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.Close();
            Response.End();
        }

    protected void btnExportWord_Click(object sender, EventArgs e)
    {
            ExportGridView("GridData.doc", "application/vnd.ms-word");
     }

        public override void VerifyRenderingInServerForm(Control control)
        {
            
        }

GridView Export To Excel in ASP.NET & C#

In this article we will see how to export grid-view to excel or word.

Step 1 : Create a new database in SQL server or if you have a database already go to step 2.

CREATE DATABASE (YOUR DATABASE NAME);

Step 2 : Create a table in the database.

CREATE TABLE Employee
(
    EmployeeID INT,
    Name Varchar(250),
    Salary Decimal (10,2)

);

Step 3 : Insert some sample data to the table.

INSERT INTO Employee VALUES (1,'Scott',1000);
INSERT INTO Employee VALUES (2,'John',1100);
INSERT INTO Employee VALUES (3,'Phil',1200);
INSERT INTO Employee VALUES (4,'Peter',1300);
INSERT INTO Employee VALUES (5,'Jose',1400);

INSERT INTO Employee VALUES (6,'Morgan',1500);


Step 4 : Now Add a WebForm to your Project and add the GridView Control and Button to Export the Data.

 <asp:GridView ID="GridView1" runat="server"></asp:GridView>
  <asp:Button ID="btnExportExcel" runat="server" Text="Export To Excel" OnClick="btnExportExcel_Click" />

Step 5 : Add the following code to your Page.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
            string connectionString = "Data Source=.SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True";
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM Employee";
                cmd.Connection = con;
                con.Open();

                SqlDataReader dr = cmd.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);

                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        private void ExportGridView(string fileName, string contentType)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            Response.Charset = "";
            Response.ContentType = contentType;

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GridView1.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.Close();
            Response.End();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
             ExportGridView("GridData.xls", "application/vnd.ms-excel");
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            
        }


Monday, October 13, 2014

Find Nth highest salary - SQL database

In this article i will explain how to find the 1st,2nd, 3rd and nth highest salary from the SQL server.

Step 1 : Create a new database in SQL server or if you have a database already go to step 2.

CREATE DATABASE (YOUR DATABASE NAME);

Step 2 : Create a table in the database.

CREATE TABLE Employee
(
    EmployeeID INT,
    Name Varchar(250),
    Salary Decimal (10,2)

);

Step 3 : Insert some sample data to the table.

INSERT INTO Employee VALUES (1,'Scott',1000);
INSERT INTO Employee VALUES (2,'John',1100);
INSERT INTO Employee VALUES (3,'Phil',1200);
INSERT INTO Employee VALUES (4,'Peter',1300);
INSERT INTO Employee VALUES (5,'Jose',1400);

INSERT INTO Employee VALUES (6,'Morgan',1500);

Step 4 : Now lets see how to write a query to get the 1st,2nd, 3rd or nth highest salary.

1st highest salary

Select Max(Salary) from Employee where Salary NOT IN ( Select TOP (2-1) Salary from Employee ORDER BY Salary DESC)

Result : 1500

2nd highest salary

Select Max(Salary) from Employee where Salary NOT IN ( Select TOP (3-1) Salary from Employee ORDER BY Salary DESC)

Result : 1400

Nth highest salary

Select Max(Salary) from Employee where Salary NOT IN ( Select TOP (n-1) Salary from Employee ORDER BY Salary DESC)

where n will be replaced by the positive integer (1,2,3,4....n) to get the 1st or 2nd, 3rd or
4th  and nth salary.


In other cases we need to get the details of the employees like (EmployeeID,Name,Salary) along with the salary then we can use the following query.

Select * from Employee e1 where (n-1) = (select Count(distinct(Salary)) from Employee e2 where e2.Salary > e1.Salary )

where n will be replaced by the positive integer (1,2,3,4....n) to get the 1st or 2nd, 3rd or
4th  and nth salary.



Happy Coding..!!!