Saturday, February 25, 2012

Alter Table ,add Column ,alter Column datatype

Adding column

You can add new columns to an existing table. 

ALTER TABLE [dbo].[TableName]
ADD   NameOfNewColumn Varchar(500) NULL  

GO

Alter column

You can add modify an existing column
ALTER TABLE [dbo].[TableName]
 
ALTER COLUMN [NameOfNewColumn ]  int NULL

GO

Drop column

You can add modify an existing column
ALTER TABLE [dbo].[TableName]
Drop
[NameOfNewColumn ]  int

GO 

For more details visit msdn link

Happy Living...
Happy Concepts...
Happy Coding...

Friday, February 24, 2012

Post Form Data using jQuery $.post() or jQuery.post()

Post Form Data using jQuery $.post() or jQuery.post()


// script tag in html page

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

var txtOrderId= $("#txtOrderId").val(); // assuming form1 is the id of the form we are trying to submit
var url= "controllerName/actionName" // set target url

$.post(url,{OrderId:txtOrderId},function(res){
// process Response Data
});

});

//  Controller Action

public ActionResult actionName(int OrderId)
{
// TO do task
return resultstring;
}

Name specified in Red should match otherwise we wont be able to get values on Action method.

But if think same we cam do to post form data then this is not the case where it will work. To post form data
we need some changes in code as specified below:


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

var formData= $("#form1").serialize(); // assuming form1 is the id of the form we are trying to submit
var url= "controller/action" // set target url

$.post(url,formData,function(res){
// process Response Data
});

});
//  Controller Action

public ActionResult actionName(OrderModel modelData) // assuming view is strong typed view
{
// TO do task
return resultstring;
}

public ActionResult actionName(FormCollection modelData) // assuming view is not strong typed view
{
// TO do task
return resultstring;
}

in this case we don't need to map parameter in action method and post parameters.

Edit: 3 May 2012

A few days back i was caught in a situation where i had to send some other parameter along with formData so initial i wasnt aware of what should i need to do but with the help of my friend (Rohit Rao)  i got this solution.
so if we have to send additional parameter with formdata

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

var formData= $("#form1").serialize(); // assuming form1 is the id of the form we are trying to submit
var url= "controller/action?param1=val1&param2=val2" // set target url Line:1
// url= "controller/action"                        Line:2
$.post(url,formData,function(res){
// process Response Data
});
});

Line 1 with query sting parameter and Line 2 is without parameter we can call same action with following action method definition.

//  Controller Action

public ActionResult actionName(string param1="",string param2="",OrderModel modelData) // assuming view is strong typed view
{
// TO do task
return resultstring;
}
we have assigned default values to param1 and param2 in the case where both are missing from query string parameter.

Note: I am not sure about below action method because it isn't tested  but as much as i know there isn't any reason it shouldn't work.
public ActionResult actionName(string param1="",string param2="",FormCollection modelData) // assuming view is not strong typed view
{
// TO do task
return resultstring;
}



I hope this will help you.

Happy Living...
Happy Concept...
Happy Coding....

Monday, February 13, 2012

Export Html Table to Excel in Asp.net MVC

Export Html Table to Excel in Asp.net

function Export()   {  
    $
('#yourHiddenFieldId').val() = $('#yourTable').table2CSV({delivery:'value'});
    __doPostBack
('#yourExportBtnId', '');   }
 
// c#   if(Page.IsPostBack)   {
   
if(!String.IsNullOrEmpty(Request.Form[yourHiddenField.UniqueId]))
   
{
       
Response.Clear();
       
Response.ContentType = "text/csv";
       
Response.AddHeader("Content-Disposition", "attachment; filename=TheReport.csv");
       
Response.Flush();
       
Response.Write(Request.Form[yourHiddenField.UniqueID]);
       
Response.End();
   
}   } 


/// using Asp.net MVC
1) Add line in .aspx

<div id="mydiv"></div>

2) Add script to create iframe with a form tag

$(document).ready(function(){
$("#mydiv").hide();
 $("#mydiv").append('<iframe id="iframe1" href="#"> </iframe>');
        function replaceAll(txt, replace, with_this) { return txt.replace(new RegExp(replace, 'g'), with_this); }
        setTimeout(function Func1() {
            $("#iframe1").contents().find("body").append('<form id="exportform" action="ExportToExcel" method="post" target="_self"><input type="hidden" id="area1" name="area1" value=""/> <input type="submit" id="b1" value="submit"/><input type="hidden" id="area2" name="area2" value=""/></form>');
        }, 50);
        });

3)  Add Script to export button

  $("#btnExport").click(function () {
                        
            var arrTop = [];
            arrTop[0] = "Test Center:" + "|" + testCenter + "|" + "Program:" + "|" + program +"|";
            arrTop[1] = "Requestor:" + "|" + requestor + "|" + "Project:" + "|" + project +"|";
            arrTop[2] = "Department:" + "|" + department + "|" + "Project Number:" + "|" + projectNo ;

           
            //code for results grid
            var Columns = jQuery("#tblData thead tr").map(function() {
            var cells = "";
            jQuery(this).find('th').each(function() {
            if (cells.length > 0) {
                cells += ',' + jQuery(this).text();
            } else
            {
                cells += jQuery(this).text();
            }
            });
            return { ColumnNames: cells };
            }).get();
           
           
            //alert(Columns);
           
            var Rows = jQuery("#tblData tbody tr").map(function() {
             var cells = "";
            jQuery(this).find('td').each(function() {
              var celValue = jQuery(this).text();
               if (cells.length > 0) {
                 cells += ',' + celValue.replace(/,/g, ';');
               } else {
                 cells += celValue.replace(/,/g, ';');
               }
             });
             return { row: cells };
            }).get();
            var tableCSV = { "Columns": Columns, "Rows": Rows };
            var array = typeof tableCSV != 'object' ? JSON.parse(tableCSV) : tableCSV;
           
            var str = '';
            for (var i = 0; i < array.length; i++) {
                var line = '';
                for (var index in array[i]) {
                    line += array[i][index] + ',';
                }
                line.slice(0,line.Length-1);
                str += line + '\r\n';
               
            }
          
             var x = JSON.stringify(tableCSV);
            var prog=  "<%= Url.RouteUrl(new { controller = "controllerName", action = "ExportToExcel"}) %>";
                      var x = JSON.stringify(tableCSV);
             $($("#iframe1").contents().find('input')[0]).val(x);
              $($("#iframe1").contents().find('input')[1]).val(arrTop);
            $($("#iframe1").contents().find("input")[2]).trigger("click");
        });

4. Add action method to controller

 [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ExportToExcel(string exportString)
        {
            exportString = Request.Form.GetValues(0)[0];
            string topTab = Request.Form.GetValues(1)[0];
            string fileName;
            fileName = "test1.xls";
            HtmlTable tempTabParam = new HtmlTable();
            //HtmlTableRow paramRow = null;
            //HtmlTableCell paramCell = null;
            string[] topArr = topTab.Replace(',', ' ').Split('|');
            HtmlTableRow paramRow1 = new HtmlTableRow();
            HtmlTableCell paramCell1 = new HtmlTableCell();
            paramCell1.InnerText = topArr[0].ToString();
            paramRow1.Cells.Add(paramCell1);
            HtmlTableCell paramCell2 = new HtmlTableCell();
            paramCell2.InnerText = topArr[1].ToString();
            paramRow1.Cells.Add(paramCell2);
            HtmlTableCell paramCell3 = new HtmlTableCell();
            paramCell3.InnerText = topArr[2].ToString();
            paramRow1.Cells.Add(paramCell3);
            HtmlTableCell paramCell4 = new HtmlTableCell();
            paramCell4.InnerText = topArr[3].ToString();
            paramRow1.Cells.Add(paramCell4);
            tempTabParam.Rows.Add(paramRow1);
            HtmlTableRow paramRow2 = new HtmlTableRow();
            HtmlTableCell paramCell5 = new HtmlTableCell();
            paramCell5.InnerText = topArr[4].ToString();
            paramRow2.Cells.Add(paramCell5);
            HtmlTableCell paramCell6 = new HtmlTableCell();
            paramCell6.InnerText = topArr[5].ToString();
            paramRow2.Cells.Add(paramCell6);
            HtmlTableCell paramCell7 = new HtmlTableCell();
            paramCell7.InnerText = topArr[6].ToString();
            paramRow2.Cells.Add(paramCell7);
            HtmlTableCell paramCell8 = new HtmlTableCell();
            paramCell8.InnerText = topArr[7].ToString();
            paramRow2.Cells.Add(paramCell8);
            tempTabParam.Rows.Add(paramRow2);
            HtmlTableRow paramRow3 = new HtmlTableRow();
            HtmlTableCell paramCell9 = new HtmlTableCell();
            paramCell9.InnerText = topArr[8].ToString();
            paramRow3.Cells.Add(paramCell9);
            HtmlTableCell paramCell10 = new HtmlTableCell();
            paramCell10.InnerText = topArr[9].ToString();
            paramRow3.Cells.Add(paramCell10);
            HtmlTableCell paramCell11 = new HtmlTableCell();
            paramCell11.InnerText = topArr[10].ToString();
            paramRow3.Cells.Add(paramCell11);
            HtmlTableCell paramCell12 = new HtmlTableCell();
            paramCell12.InnerText = topArr[11].ToString();
            paramRow3.Cells.Add(paramCell12);
            tempTabParam.Rows.Add(paramRow3);
           
            tempTabParam.BorderColor = ConsoleColor.DarkRed.ToString(); ;
           
           
           
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            HtmlTable tempTable = new HtmlTable();
            tempTable.Border = 1;
            HtmlTableRow headRow = new HtmlTableRow();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            TableData data = serializer.Deserialize<TableData>(exportString);
            HtmlTableCell cell = null;
            columns[] col = data.Columns;
            string[] arr = col[0].ColumnNames.Replace("\n", "").Replace(" ", "").Split(',');
            for (int i = 0; i <= arr.Length - 1; i++)
            {
                cell = new HtmlTableCell();
                cell.InnerText = arr[i].ToString();
                cell.BgColor = ConsoleColor.DarkRed.ToString();
                headRow.Cells.Add(cell);
            }
            tempTable.Rows.Add(headRow);
           
            rows[] arr1 = data.Rows;
            HtmlTableRow tabRow = null;
            HtmlTableCell tbCell = null;
            string[] rowArr = null;
            foreach (rows dataRow in data.Rows)
            {
                tabRow = new HtmlTableRow();
                rowArr = dataRow.row.Replace("\n", "").Replace(" ", "").Split(',');
                for (int j = 0; j <= rowArr.Length - 1; j++)
                {
                    tbCell = new HtmlTableCell();
                    tbCell.InnerText = rowArr[j].ToString();
                    tabRow.Cells.Add(tbCell);
                }
                tempTable.Rows.Add(tabRow);
            }
          
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            tempTabParam.RenderControl(hw);
            tempTable.RenderControl(hw);
           
            string filePath = HttpContext.Server.MapPath("~/content/");
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return File(encoding.GetBytes(hw.InnerWriter.ToString()), "application/excel", fileName);
           
        }

Updated :

public class columns
{
public string ColumnNames;
}

public class rows
{
public string row;
}

public class TableData
{
public columns[] Columns;
public rows[] Rows;
}

Friday, February 10, 2012

How to build jQuery Plugin

How to build a jQuery Plugin?

Here is the link of one of the best tutorial i read on internet and i'll also recommand you to read this article.
Before some creates a new jQuery Plugin it must be able to understand the basics of Javascript and jQuery.
This tutorial is very good source of information for those who are looking for a good tutorial on jQuery.

http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner

Call by Value and Call by Reference in Javascript

Call by Value and Call by Reference in Javascript

Call By Value
ex:
function ByValue( o)
{
o*=o;

}
var x=4;
ByValue(x);
alert(x);// result will be 4

Call By Reference
ex:
var obj= new Object();
obj.newProperty=4;

ByRef(obj);
function ByRef(obj)
{
obj.newProperty*=obj.newProperty;
}

alert(obj.newProperty);// result will be 16

Happy Living...
Happy Coding...
Happy Concepts...















Thursday, February 9, 2012

ASP.NET Inline Tags

ASP.NET Inline Tags

There are six type of asp.net Inline Tags.


1. Most basic Inline Tag:
<%..........................%> runs normal code
 <% for(int i = 0; i < 12; i++) %>
       <% { Response.Write("<br>" + i.ToString()); }%>



2. Single Pieces of Info:
<%=...........................%>
Hello <%= name %>!

3. Server side comment - must have access to the code to see
<%--...............................--%>
<%--That's all folks--%>


4. Binding Expressions, such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:

<%#.............................%>

<table>
    <tr>
      <td align=right>
        <b>Employee ID:</b>
      </td>
      <td>
        <%# Eval("EmployeeID") %>
      </td>
    </tr>
    <tr>
      <td align=right>
        <b>First Name:</b>
      </td>
      <td>
        <asp:TextBox ID="EditFirstNameTextBox" RunAt="Server"
          Text='<%# Bind("FirstName") %>' />
      </td>
    </tr>
</table>



6. Expressions (not code) often DataSources:

<%$......................................%>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
    SelectCommand="SELECT * FROM [Employees]"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>">
</asp:SqlDataSource>