Sunday, 6 August 2017

ExcelDataReader to read excel and upload bulk data in Asp.net MVC

What we want to achieve?
We want to insert bulk question and its options in question table and Option table respectively
using excel sheet as per given excel format. 

We'll be reading question and all options for that question question by question using excel data reader and implementing bulk insert.

Add library for ExcelDataReader :
  1. Install the ExcelDataReader base package to use the "low level" reader interface. 
  2. Install the ExcelDataReader.DataSet extension package to use the AsDataSet() method to populate a System.Data.DataSet. 

We'll passing all option as a single string using separator +|+ and *|* like as given below :
Option+|+true+|+1*|*Option2+|+false+|+2 that is Option+|+Iscorrect+|+OrderBy*|* to save in option table.

In View : 

@{
    ViewBag.Title = "BulkUpload";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="maincontainer">
    <div id="divExcel" class="divExcelUP">
        @using (Html.BeginForm("BulkUpload", "Question", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {      
            <div class="editor-label">
                Select File :
            </div>
            <div class="editor-field">
                <input type="file" id="flExcel" name="postedFile" />
                <div id="errflExcel" class="divErr"></div>
            </div>
            <div class="editor-label">

            </div>
            <div class="editor-field">
                <input class="Button" id="btnUpload" type="submit" value="Upload" />
            </div>        
        }
    </div>
    <div class="clearfix"></div>
</div>

@section scripts{
    <script>
        $(document).ready(function () {
            $('div[id^="err"]').html("");

            var fileName = document.getElementById('flExcel').value;
            $("#btnUpload").click(function () {
                if ($("#flExcel").val() != "") {                
                }
                else {
                    $("#errflExcel").html("Please select file for bulk upload.");
                }
            });
        });
    </script>

}

In Controller : 

public ActionResult BulkUpload()
        {
            return View();
        }
        [HttpPost]
        public ActionResult BulkUpload(HttpPostedFileBase postedFile)
        {
            string ext = Path.GetExtension(postedFile.FileName);
            if (ext == ".xls" || ext == ".xlsx")
            {                
                string filePath = "";
                filePath = "/BulkUpload/" + "QA" + ext;
                string path = Server.MapPath(filePath);
                postedFile.SaveAs(path);
                // Reading excel file using excel data reader.
                using (var stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = ExcelReaderFactory.CreateReader(stream))
                    {
                        DataSet result = reader.AsDataSet();
                        DataTable dt = result.Tables[0];

                        int quesColumnCount = dt.Columns.Count;
                        int quesRowCount = dt.Rows.Count;
                        int quesID = Convert.ToInt32(dt.Rows[2][0]);
                        Question question = new Question();
                        QuestionDA questionDA = new QuestionDA();

                        string Option = string.Empty;

                        for (int row = 1; row <= quesRowCount - 1; row++)
                        {
                            if (quesID == Convert.ToInt32(dt.Rows[row][0]))
                            {                              
                                if (Convert.ToString(dt.Rows[row][1]) == "Q")
                                {
                                    question.Title = Convert.ToString(dt.Rows[row][2]);
                                    question.Description = Convert.ToString(dt.Rows[row][3]);
                                    question.QueImageURL = Convert.ToString(dt.Rows[row][4]);
                                    question.BaseValue = Convert.ToInt32(dt.Rows[row][5]);
                                    question.ModuleId = Convert.ToInt32(dt.Rows[row][6]);
                                    question.QuestionType = Convert.ToString(dt.Rows[row][7]);
                                }
                                else if (Convert.ToString(dt.Rows[row][1]) == "A")
                                {
                                    Option += Convert.ToString(dt.Rows[row][2]) + "+|+" + Convert.ToString(dt.Rows[row][3]) + "+|+";
                                    Option += Convert.ToInt32(dt.Rows[row][4]) + "*|*";
                                    if (row == quesRowCount - 1)
                                    {
                                        //Call function to save last set of record before exiting loop.
                                        Option = Option.Substring(0, Option.Length-3);                                     
                                        questionDA.CreateBulkQuestionOptions(question,Option);                                       
                                    }
                                }
                            }
                            else
                            {
                                //If Qid differs then call function to save data.
                                Option = Option.Substring(0, Option.Length - 3);
                                questionDA.CreateBulkQuestionOptions(question, Option);                               
                                quesID = Convert.ToInt32(dt.Rows[row][0]);
                                Option = "";
                                row--;
                            }
                        }
                    }
                }
            }
            return View();
        }

In Data Access : 

public void CreateBulkQuestionOptions(Question question, string Option)
        {
            try
            {
                int i = ExecNonQueryProc("Usp_QAModule_CreateBulkQuestionOptions",
                new SqlParameter("@Title", question.Title),
                new SqlParameter("@Description", question.Description),
                new SqlParameter("@QueImageURL", question.QueImageURL),
                new SqlParameter("@BaseValue", question.BaseValue),
                new SqlParameter("@ModuleId", question.ModuleId),
                new SqlParameter("@QuestionType", question.QuestionType),
                new SqlParameter("@CreatedOn", DateTime.Now.ToShortDateString()),
                new SqlParameter("@Options", Option));                
            }
            catch
            {
                throw;
            }
            finally
            {
                CloseConnection();
            }

        }

In Database we are using two procedures and one function in order achieve our goal with out using cursor : 

CREATE PROC [dbo].[Usp_QAModule_CreateBulkQuestionOptions]            
@Title TEXT,       
@Description TEXT,    
@QueImageURL VARCHAR(MAX),     
@BaseValue FLOAT,     
@ModuleId INT,    
@QuestionType VARCHAR(30),      
@CreatedOn DATETIME,     
@Options VARCHAR(MAX)                   
AS            
BEGIN     
  DECLARE @QId INT    
  DECLARE @Option VARCHAR(MAX)    
  
  INSERT jquestions      
  (  
  Title,     
  [Description],     
  QueImageURL,    
  BaseValue,     
  ModuleId,     
  QuestionType,     
  CreatedOn,    
  IsActive  
   )     
  VALUES    
  (  
  @Title,     
  @Description,     
  @QueImageURL,    
  @BaseValue,     
  @ModuleId,     
  @QuestionType,     
  @CreatedOn,    
  1  
   );  
  
 SET @QId= @@IDENTITY;  
  
 DECLARE @execQuery NVARCHAR(MAX);  
 SELECT @execQuery  = COALESCE(@execQuery +';' ,'') + 'EXEC [dbo].[usp_QaModule_CreateOptions] '+CAST(@QId AS VARCHAR)+', '''+ CAST(@CreatedOn AS VARCHAR) +''', '''+@QuestionType+''', ''' + Element+''', ''+|+'''  
 FROM dbo.func_split(@Options, '*|*');  
 --PRINT(@execQuery)  
 EXECUTE sp_executesql @execQuery;  
  
END

======================================================

CREATE PROCEDURE [dbo].[usp_QaModule_CreateOptions]  
    (  
  @qId INT,  
  @createdDate DATETIME,  
  @questionType VARCHAR(MAX),  
  @element    VARCHAR(MAX),  
  @delimiter VARCHAR(MAX)  
    )  
AS  
BEGIN  
 DECLARE @result BIT = 0;  
  
 ;WITH opt AS(  
  SELECT * FROM dbo.func_split(@element, '+|+')  
 )  
  
    INSERT INTO jquestionoptions            
 (  
  Id_Question,            
  [Option],            
  IsCorrect,            
  CreatedOn,            
  OptionType,        
  OrderBy  
 )            
   VALUES            
   (  
    @qId,            
    (select Element from opt where elementId = 1),                
    CAST((select Element from opt where elementId = 2) AS BIT),                
    @createdDate,         
    @questionType,  
    (select Element from opt where elementId = 3)  
   )    
  
    RETURN @result  
END

=============================================================

CREATE FUNCTION [dbo].[func_Split]  
    (  
    @DelimitedString    varchar(MAX),  
    @Delimiter              varchar(MAX)  
    )  
RETURNS @tblArray TABLE  
    (  
    ElementID   int IDENTITY(1,1),  -- Array index  
    Element     varchar(MAX)               -- Array element contents  
    )  
AS  
BEGIN  
  
    -- Local Variable Declarations  
    -- ---------------------------  
    DECLARE @Index      smallint,  
                    @Start      smallint,  
                    @DelSize    smallint  
  
    SET @DelSize = LEN(@Delimiter)  
  
    -- Loop through source string and add elements to destination table array  
    -- ----------------------------------------------------------------------  
    WHILE LEN(@DelimitedString) > 0  
    BEGIN  
  
        SET @Index = CHARINDEX(@Delimiter, @DelimitedString)  
  
        IF @Index = 0  
            BEGIN  
  
                INSERT INTO  
                    @tblArray  
                    (Element)  
                VALUES  
                    (LTRIM(RTRIM(@DelimitedString)))  
  
                BREAK  
            END  
        ELSE  
            BEGIN  
  
                INSERT INTO  
                    @tblArray  
                    (Element)  
                VALUES  
                    (LTRIM(RTRIM(SUBSTRING(@DelimitedString, 1,@Index - 1))))  
  
                SET @Start = @Index + @DelSize  
                SET @DelimitedString = SUBSTRING(@DelimitedString, @Start , LEN(@DelimitedString) - @Start + 1)  
  
            END  
    END  
  
    RETURN  
END

Part 1 : Create Sample Application Using Asp.net MVC

Adding Employee and Retrieve it and show in table using Ajax in ASP.NET MVC

Application Name : SampleMVC
Database : NorthwindDb
Class Library : SampleMVC.DA
Class Library : SampleMVC.Models



Step 1 : Adding SQLHelper.cs Class in Class Library SampleMVC.DA

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Configuration;

namespace SampleMvc.DA
{
    /// <summary>
    /// Summary description for Class_SQLHelper
    /// </summary>
    public class SQLHelper
    {
        private SqlCommand cmd = new SqlCommand();
        private SqlConnection conn;
        private bool bool_Status;
        private string str_Error;

        public SQLHelper()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ToString());
        }

        protected void OpenConnection()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
            }
            catch (Exception ex)
            {
                OperationStatus = false;
                ErrorMessage = "Error : " + ex.Message;
            }
        }

        protected void CloseConnection()
        {
            try
            {
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
            catch (Exception ex)
            {
                OperationStatus = false;
                ErrorMessage = "Error : " + ex.Message;
            }
        }

        public SqlConnection Connection
        {
            get { return conn; }
        }

        public SqlCommand Command
        {
            get { return cmd; }
            set { cmd = value; }
        }

        public bool OperationStatus
        {
            get { return bool_Status; }
            set { bool_Status = value; }
        }

        public string ErrorMessage
        {
            get { return str_Error; }
            set { str_Error = value; }
        }

        /// <summary>
        /// Constructs a SqlCommand with the given parameters. This method is normally called
        /// from the other methods and not called directly. But here it is if you need access
        /// to it.
        /// </summary>
        /// <param name="qry">SQL query or stored procedure name</param>
        /// <param name="type">Type of SQL command</param>
        /// <param name="args">Query arguments. Arguments should be in pairs where one is the
        /// name of the parameter and the second is the value. The very last argument can
        /// optionally be a SqlParameter object for specifying a custom argument type</param>
        /// <returns></returns>
        public SqlCommand CreateCommand(string qry, CommandType type, params object[] args)
        {
            SqlCommand cmd = new SqlCommand(qry, conn);
            OpenConnection();
            // Set command type
            cmd.CommandType = type;

            // Construct SQL parameters
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] is string && i < (args.Length - 1))
                {
                    SqlParameter parm = new SqlParameter();
                    parm.ParameterName = (string)args[i];
                    parm.Value = args[++i];
                    cmd.Parameters.Add(parm);
                }
                else if (args[i] is SqlParameter)
                {
                    cmd.Parameters.Add((SqlParameter)args[i]);
                }
                else throw new ArgumentException("Invalid number or type of arguments supplied");
            }

            return cmd;
        }

        /// <summary>
        /// Executes a stored procedure that returns no results
        /// </summary>ExecNonQueryProc
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>The number of rows affected</returns>
        public int ExecNonQueryProc(string proc, params object[] args)
        {
               int result = 0;        
                using (SqlCommand cmd = CreateCommand(proc, CommandType.StoredProcedure, args))
                {
                    result= cmd.ExecuteNonQuery();
                    CloseConnection();
                    return result;
                }        
        }

        /// <summary>
        /// Executes a query that returns a single value
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Value of first column and first row of the results</returns>
        public object ExecScalarProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                return cmd.ExecuteScalar();
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a SqlDataReader
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Results as a SqlDataReader</returns>
        public SqlDataReader ExecDataReaderProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                return cmd.ExecuteReader();
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a Data Set
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Results as a DataSet</returns>
        public DataSet ExecDataSetProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapt.Fill(ds);
                return ds;
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a Data Set
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <param name="args">Any number of parameter name/value pairs and/or SQLParameter arguments</param>
        /// <returns>Results as a DataTable</returns>
        public DataTable ExecDataTableProc(string qry, params object[] args)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure, args))
            {
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapt.Fill(dt);
                return dt;
            }
        }

        /// <summary>
        /// Executes a stored procedure and returns the results as a Data Set
        /// </summary>
        /// <param name="proc">Name of stored proceduret</param>
        /// <returns>Results as a DataTable</returns>
        public DataTable ExecDataTableProc(string qry)
        {
            using (SqlCommand cmd = CreateCommand(qry, CommandType.StoredProcedure))
            {
                SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapt.Fill(dt);
                return dt;
            }
        }
    }
}

Step 2 : Adding Class EmployeeDA.cs in Class Library SampleMVC.DA and inheriting it with SQLHelper.cs and call required function of SQLHelper Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SampleMvc.Models;
using System.Data.SqlClient;
using System.Data;

namespace SampleMvc.DA
{
    public class EmployeeDA : SQLHelper
    {
        public void AddEmployee(Employee emp)
        {
            try
            {
                int i = ExecNonQueryProc("Usp_AddEmployee",
                new SqlParameter("@LastName", emp.LastName),
                new SqlParameter("@FirstName", emp.FirstName),
                new SqlParameter("@Title", emp.Title),
                new SqlParameter("@Birthdate", emp.BirthDate));
            }
            catch (Exception ex)
            {
                ErrorMessage = "Error : " + ex.Message;
                OperationStatus = false;
            }
            finally
            {
                CloseConnection();
            }
        }

        public DataTable GetAllEmployees()
        {
            DataTable dt = new DataTable();
            dt = ExecDataTableProc("Usp_GetAllEmployees");
            return dt;
        }
    }
}

Step 3 : Build And Add Class Libraries in SampleMVC

Step 4 : Adding EmployeeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SampleMvc.Models;
using SampleMvc.DA;
using System.Data;
using System.Web.Script.Serialization;

namespace SampleMvc.Controllers
{
    public class EmployeeController : Controller
    {      
        public ActionResult AddEmployee()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddEmployee(Employee emp)
        {
            EmployeeDA employeeDA = new EmployeeDA();
            employeeDA.AddEmployee(emp);
            return View();
        }
        public ActionResult GetAllEmployees()
        {
            DataTable dt = new DataTable();
            EmployeeDA employeeDA = new EmployeeDA();
            dt=employeeDA.GetAllEmployees();
            String emp = ConvertDataTableTojSonString(dt);
            return Json(emp);
        }

        public String ConvertDataTableTojSonString(DataTable dataTable)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer =
                   new System.Web.Script.Serialization.JavaScriptSerializer();

            List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();

            Dictionary<String, Object> row;

            foreach (DataRow dr in dataTable.Rows)
            {
                row = new Dictionary<String, Object>();
                foreach (DataColumn col in dataTable.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                tableRows.Add(row);
            }
            return serializer.Serialize(tableRows);
        }
    }
}

Step 5 : Adding AddEmployee view

@{
    Layout = null;
}

<script src="~/Scripts/jquery-3.2.1.js"></script>
<script>
    $(document).ready(function () {
        getAllEmployees();
        $('#btnAddEmployee').click(function () {
            var employee = {};
            employee.LastName = $('#txtLastName').val();
            employee.FirstName = $('#txtFirstName').val();
            employee.Title = $('#txtTitle').val();
            employee.BirthDate = $('#txtDob').val();

            $.ajax({
                url: 'Employee/AddEmployee',
                method: 'post',
                data: '{emp: ' + JSON.stringify(employee) + '}',
                contentType: "application/json; charset=utf-8",
                success: function () {
                    getAllEmployees();
                },
                error: function (err) {
                    alert(err);
                }
            });
        });
        
        function getAllEmployees() {
            $.ajax({
                url: 'Employee/GetAllEmployees',
                dataType: "json",
                method: 'post',
                success: function (data) {
                    var employeeTable = $('#tblEmployee tbody');
                    employeeTable.empty();                 
                    $(JSON.parse(data)).each(function (index, emp) {
                       
                            employeeTable.append('<tr><td>' + emp.LastName + '</td><td>'
                            + emp.FirstName + '</td><td>' + emp.Title
                            + '</td><td>' + emp.BirthDate + '</td></tr>');
                    });
                },
                error: function (err) {
                    alert(err);
                }
            });
        }
    });
</script>

<div style="padding: 30px;">
    Last Name<br />
    <input type="text" id="txtLastName" /><br />
    First Name<br />
    <input type="text" id="txtFirstName" /><br />
    Title
    <br />
    <input type="text" id="txtTitle" /><br />
    DOB<br />
    <input type="text" id="txtDob" />
    <br />
    <br />
    <input type="button" value="Save" id="btnAddEmployee" />
</div>

@*Table to display data *@

    <table id="tblEmployee" border="1" style="border-collapse:collapse">
        <thead>
            <tr>
                <th>Last Name</th>
                <th>First Name</th>
                <th>Title</th>
                <th>DOB</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table> 

Monday, 24 July 2017

DropdownList in MVC Strongly Typed

View

 <div class="editor-label">
            Country
        </div>
        <div class="editor-field">
         
            @Html.DropDownListFor(model=>model.CountryId, new SelectList((ViewBag.Countries) as SelectList, "Value", "Text"), "Select")
        </div>


-----------------------------------
Controller
  CountryDA countryda = new CountryDA ();
 ViewBag.Countries =new SelectList(countryda.ReadAllCountry(), "CountryId", "CountryName", _country.CountryId);
     
-------------------------------
DATA Access

  public List<Country> ReadAllCountry()
        {
            List<Country> country = new List<Country>();
            try
            {
                using (SqlConnection con = new SqlConnection(connectionstring))
                {
                    SqlCommand com = new SqlCommand("Usp_ReadAllCountry", con);
                    com.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader dr = com.ExecuteReader();

                    while (dr.Read())
                    {
                        country.Add(new Country { CountryId = Convert.ToInt32(dr["CountryId"]), CountryName = Convert.ToString(dr["CountryName"]) });
                    }
                }
            }
            catch
            {
                throw;
            }
            return country;
        }

---------------------------------------
Model
   public class Country
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }
    }


       

Sunday, 16 July 2017

Bind data in MVC using Datatables.net Jquery Plugin

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table. DataTables is a table enhancing library which adds features such as paging, ordering, search, scrolling and many more to a static HTML page. A comprehensive API is also available that can be used to manipulate the table.
 Reference taken : http://csharp-video-tutorials.blogspot.com/2015/08/jquery-datatables-get-data-from.html

In Controller Action Methods.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication3.Models;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace MvcApplication3.Controllers
{
    public class homeController : Controller
    {
        public ActionResult Index()
        {
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            List<Employee> employees = new List<Employee>();
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetEmployees", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Employee employee = new Employee();
                    employee.Id = Convert.ToInt32(rdr["Id"]);
                    employee.FirstName = rdr["FirstName"].ToString();
                    employee.LastName = rdr["LastName"].ToString();
                    employee.Gender = rdr["Gender"].ToString();
                    employee.JobTitle = rdr["JobTitle"].ToString();
                    employee.WebSite = rdr["WebSite"].ToString();
                    employee.Salary = Convert.ToInt32(rdr["Salary"]);
                    employee.HireDate = Convert.ToDateTime(rdr["HireDate"]);
                    employees.Add(employee);
                }
            }
            JavaScriptSerializer js = new JavaScriptSerializer();
            string JSONString = js.Serialize(employees);

            ViewBag.datast = JSONString;
            return View();
        }  
    }
}

In Index.cshtml view

@{
    Layout = null;
}

<link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.css" />
<link rel="stylesheet" type="text/css"
    href="https://cdn.datatables.net/1.10.15/css/dataTables.semanticui.min.css" />



<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.semanticui.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.semanticui.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.2/js/dataTables.select.min.js"></script>
<script src="../../extensions/Editor/js/dataTables.editor.min.js"></script>
<script src="../../extensions/Editor/js/editor.semanticui.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
       
        var dataset =@Html.Raw((String)ViewBag.datast)

        $('#datatable').dataTable({
            edit: true,
            data: dataset,
        columns: [
                    { 'data': 'Id' },
                    { 'data': 'FirstName' },
                    { 'data': 'LastName' },
                    { 'data': 'Gender' },
                    { 'data': 'JobTitle' },
                    {
                        'data': 'WebSite',
                        'sortable': false,
                        'searchable': false,
                        'render': function (webSite) {
                            if (!webSite) {
                                return 'N/A';
                            }
                            else {
                                return '<a href=' + webSite + '>'
                                    + webSite.substr(0, 10) + '...' + '</a>';
                            }
                        }
                    },
                    {
                        'data': 'Salary',
                        'render': function (salary) {
                            return "$" + salary;
                        }
                    },
                    {
                        'data': 'HireDate',
                        'render': function (jsonDate) {
                            var date = new Date(parseInt(jsonDate.substr(6)));
                            var month = date.getMonth() + 1;
                            return month + "/" + date.getDate() + "/" + date.getFullYear();
                        }
                    }
        ]


    });
    });
</script>


<div style="width: 900px; border: 1px solid black; padding: 3px">
    <table id="datatable" class="ui celled table" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Gender</th>
                <th>Job Title</th>
                <th>Web Site</th>
                <th>Salary</th>
                <th>Hire Date</th>
            </tr>
        </thead>
    </table>
</div>

Copy to Clipboard

Copying text to the clipboard shouldn't be hard. A very simple example is as given below : 

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btnCopy").click(function () {
            $("#txtData").select();
            document.execCommand("Copy");
        });
    })
</script>


<input type="text" id="txtData" />
<input type="button" value="Copy" id="btnCopy" />

Saturday, 15 July 2017

Validate textbox using textbox id as parameter.


Validate textbox using textbox id as parameter.    
========================================================================
     <script type="text/javascript">
        function checkTextField(field) {
            var _txtSearch = document.getElementById(field).value;
            if (_txtSearch == "") {
                alert("Please enter your search text.");
                document.getElementById(field).focus();
                return false;
            }
        }
    </script>


  <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/searchbar.jpg" OnClientClick="return checkTextField('txt_search')"
    OnClick="ImageButton1_Click" Style="width: 34px" />

========================================================================

      <script type="text/javascript">

        function Validation() {

            var mobrange = /^[0-9]{10}$/;
            var exp = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;

            var name = document.getElementById('<%=txt_name.ClientID%>').value;
            var email = document.getElementById('<%= txt_email.ClientID %>').value;
            var contact = document.getElementById('<%=txt_phone.ClientID%>').value;
            if (name == "") {
                alert("Please Enter Your Name.");
                document.getElementById('<%=txt_name.ClientID%>').focus();
                return false;
            }
            if (email == "") {
                alert('Email field can not be blank');
                document.getElementById("<%=txt_email.ClientID%>").focus();
                return false;
            }
            if (exp.test(email) == false) {
                alert('Email should be in proper format (eg: xyx@gmail.com)');
                document.getElementById("<%=txt_email.ClientID%>").focus();
                return false;
            }
            if (contact == "") {
                alert("Please Enter Your Mobile Number.");
                document.getElementById("<%=txt_phone.ClientID%>").focus();
                return false;
            }
            if (mobrange.test(contact) == false) {
                alert("Mobile number is not valid.");
                document.getElementById("<%=txt_phone.ClientID%>").focus();
                return false;
            }
            if (contact.length > 10 || contact.length < 10) {
                alert("Mobile number is not valid.");
                document.getElementById("<%=txt_phone.ClientID%>").focus();
                return false;
            }
        }
       
    </script>

Custom Validator for Checkbox inside gridview checked or not

Alert using Custom Validator for Checkbox inside gridview checked or not 

 <script type="text/javascript">  
function Validate(sender, args) {
            var gridView = document.getElementById("<%=grid_ECL.ClientID %>");
            var checkBoxes = gridView.getElementsByTagName("input");
            for (var i = 0; i < checkBoxes.length; i++) {
                if (checkBoxes[i].type == "checkbox" && checkBoxes[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }          
   </script>
========================================================================
   <asp:CustomValidator ID="CustomValidator1" runat="server" ValidationGroup="print" ErrorMessage="Please select at least one record." ClientValidationFunction="Validate" ForeColor="Red"></asp:CustomValidator>

========================================================================

 <asp:Button ID="btnA4" runat="server" Text="Print A4" OnClick="btnA4_Click" ValidationGroup="print" />