-->

Saturday, April 19, 2014

How to Upload File/Files in Asp.Net MVC

Uploading a file is need some Html code with setting the encoding type to multipart/form-data and the method of form is post. After setting this type, programmer have to use file upload control having the property name and id. Here is the code written in the view page:

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

This code will place a file upload control to browse a single file of any type of extension and a submit button which will help to post this file to action. Now our action method must have a specific parameter written below in the code:

public ActionResult GetValues(HttpPostedFileBase file)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("Path/"), fileName);
file.SaveAs(path);
…………
………..

In this action method programmer can easily get this file and can save this file as done in above code. This code is for uploading/accessing single file, what if programmer want to upload multiple files.

To upload multiple files in view page, just change the file upload control as written below:

<input type="file" name="files" id="files" multiple/>

In the action method of controller change the parameter as written below:

public ActionResult GetValues(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{

}
……..
……..
All the files can easily accessed and using the foreach loop, programmer can perform individual action with these files. If programmer want to limit the no. of files to be uploaded by the user, no. of file upload control can be used in the view page and action code will remain same as is.

What if two files are uploaded with the same name, the previous file will be overwritten by the new one. To overcome with these issues we can rename the file when we are saving them like unique identifier or may be other unique name. Programmer can also perform some validation discussed earlier.

How to get last index of 2D array in c# ASP.NET

Suppose you have 2D array in the form of x and y axis, You want to access last index of both axis. Now at this time, you can consider x as row and y as column. Here we use GetUpperBound ( ) method for accessing last index of array. Lets take an example, in which we will pass 0 and 1 in the GetUpperBound ( ) method. Here 0 for first axis and 1 for second axis.
<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Clike"
        BackColor="#99CCFF" />
    <div>
   
        <asp:Label ID="Label1" runat="server" BackColor="Yellow"></asp:Label>
   
    </div>
    </form>

Code Behind
protected void Button1_Click(object sender, EventArgs e)
    {
        {
            string[,] fruits = new string[4, 2]
        {
            {"Red","Apple"},
            {"Orange","Orange"},
            {"Yellow","Banana"},
            {"Green","Mango"},          
        };
            int rows = fruits.GetUpperBound(0);            
            int columns = fruits.GetUpperBound(1);
            Label1.Text = "index of last element of first dimension [0] in fruits array: " + rows.ToString();
            Label1.Text += "<br />index of last element of second dimension [1] in fruits array: " + columns.ToString();
            Label1.Text += "<br /><br />two dimension fruits array elements.........<br />";
            for (int currentRow = 0; currentRow <= rows; currentRow++)
            {
                for (int currentColumn = 0; currentColumn <= columns; currentColumn++)
                {
                    Label1.Text += fruits[currentRow, currentColumn] + " ";
                }
                Label1.Text += "<br />";
            }
        }
Code Generate the following output
How to get last index of 2D array in c# ASP.NET


Friday, April 18, 2014

Add weeks in existing date ASP.NET example

Introduction

Using Add Days method  you can add weeks in integer (converts weeks in days), Object will be updated with new date. This method is used where you want to calculate date after some days. Like Library management project. Lets take an simple example

<form id="form1" runat="server">
    <asp:Button ID="Button1"
    runat="server"
    BackColor="#99CCFF"
    onclick="Button1_Click"
    Text="Click" />
    <div>  
    <asp:Label ID="Label1"
    runat="server"
    BackColor="Yellow"></asp:Label>  
    </div>
    </form>
Code Behind 
protected void Button1_Click(object sender, EventArgs e)
        {        
            DateTime today = DateTime.Today;        
            DateTime after2week = today.AddDays(14);            
            DateTime after4weeks = today.AddDays(28);
            Label1.Text = "today= " + today.ToLongDateString();
            Label1.Text += "<br /><br />after added two weeks with today=";
            Label1.Text += after2week.ToLongDateString();
            Label1.Text += "<br /><br />after added 4 weeks with today=";
            Label1.Text += after4weeks.ToLongDateString();

        }
Code generate the following code

Add weeks in existing date ASP.NET example

Add days in existing date ASP.NET example

Introduction

Using AddDays method  you can add Days in integer, Object will be updated with new date. This method is used where you want to calculate date after some days. Like Library management project. Lets take an simple example
<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
        runat="server"
        BackColor="#66CCFF"
        onclick="Button1_Click" Text="Click" />  
    </div>
        <asp:Label ID="Label1"
        runat="server"
        BackColor="Yellow"></asp:Label>
    </form>
Code Behind-
protected void Button1_Click(object sender, EventArgs e)
        {          
            DateTime today = DateTime.Today;
            DateTime after2Days = today.AddDays(2);
            Label1.Text = "today= " + today.ToLongDateString();
            Label1.Text += "<br /><br />after added 2 days with today= ";
            Label1.Text += after2Days.ToLongDateString();

        }  
OutPut-


Add days in existing date ASP.NET example

Add months in existing date example in ASP.NET

Introduction

Using AddMonths method  you can add months in integer, Object will be updated with new date. This method is used where you want to calculate date after some months. Like Library management project. Lets take an simple example


<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
        runat="server"
        onclick="Button1_Click"
        Text="Click"
        BackColor="#99CCFF" />  
    </div>
        <asp:Label ID="Label1"
        runat="server"
        BackColor="Yellow"></asp:Label>
    </form>
CodeBhindeCode-
 protected void Button1_Click(object sender, EventArgs e)  
        {        
            DateTime now = DateTime.Now;        
            DateTime after3Months = now.AddMonths(3);
            Label1.Text = "now = " + now.ToLongDateString();
            Label1.Text += "<br /><br />after added 3 months to now= ";
            Label1.Text += after3Months.ToLongDateString();

        }
OutPut
 Add months in existing date example in ASP.NET

Example of Array.Copy ( ) method in ASP.NET

Introduction

If you want to run array until at specified position, you can simply use copy ( ) method. In this method define some parameters. Like array name, index where you want to start from,ending index etc.
<form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click"
        BackColor="#99CCFF" />
    <div>  
        <asp:Label ID="Label1" runat="server" BackColor="Yellow"></asp:Label>  
    </div>
    </form>


Code behind code
 protected void Button1_Click(object sender, EventArgs e)
    {
        {
            string[] Fruits = new string[]
        {
            "Apple",
            "Banana",
            "Mango",
            "Orange",  
        };
            Label1.Text = "Fruits array: <br />";
            foreach (string s in Fruits)
            {
                Label1.Text += s + "<br />";
            }        
            int length = 3;          
            int index = 1;
            string[] copiedarray = new string[length];
            Array.Copy(Fruits, index, copiedarray, 0, length);
            Label1.Text += "<br /> New array from Fruits array [index no 1 to 3]:<br />";
            foreach (string s in copiedarray)
            {
                Label1.Text += s + "<br />";
            }
        }
OutPut-

Wednesday, April 16, 2014

Computer Programming : How to change data without postback in ASP.NET

News From Computer Programming: In ASP.NET you can't change the data without post-back, if you want to change data without post back, you can use AJAX technology. In previous article we have already learned more about AJAX like, How to install AJAX control Toolkit to the Toolbox or many more. Today we will learn How to update your GridView data in every seconds, for this you can use Timer control.
The Timer control is used for updating contents of the UpdatePanel control at predefined intervals. Single Timer control can refresh  more than one UpdatePanel control simultaneously. The Timer control  has an Interval property for defining the timer limit after which the content gets refreshed. When this interval limit gets over, the Tick event is raised . You can handle this event for updating the content values defined in the UpdatePanel control. The Timer control can be used either inside the UpdatePanel control or outside the UpdatePanel control. Now, let's try to understand the UpdatePanel control in both ways.

Timer control Inside the UpdatePanel Control

To use the Timer control inside the UpdatePanel control, drag and drop from the Toolbox as a sub-element of the <ContentTemplate>tag and follow the following steps:
1. Set the interval property of the Timer control as 1000 that equal to 1 second as it takes value in milliseconds.
2.Now, double-click the Timer control in design mode. It will generate event handler function in the code-behind file to handle the Tick event.

Timer Control Outside the UpdatePanel Control

You can use the Timer control outside the UpdatePanel control. This approach is appropriate when there are more than one UpatePanel control in the same Web page and you need to use same Timer control for all or some of them. To do so, you need to perform some changes in your application. However, these changes will not affect the output of your application. First, drag-and-drop the Timer control from the toolbox. Drop it after the ScriptManager control and before the UpdatePanel control; and configure its properties in the following way:
The ScriptManager Tag:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>


The Timer control outside the UpdatePanel control and after the ScriptManager Tag:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:Timer ID="Timer1" runat="server" Interval ="1000" OnTick ="Timer1_Tick"></asp:Timer>
Configure the UpdatePanel Control's <Triggers> Element for referencing the timer control in the following way:

   <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID ="Timer1" EventName ="Tick" />
            </Triggers>
        </asp:UpdatePanel>
Lets take a simple example to update GridView Data:
Step-1 : Add ScriptManager and UpdatePanel control after Form tag
Step-2 : Add Content template inside UpdatePanel Control.  
Step-3 : Add Timer control inside ContentTemplate with Tick event and Interval property.
Step-4 : Also add GridView control inside the Content Template.
Step-5 : Bind GridView Control in Tick event.
 Complete Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">



        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
       
       
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
           <ContentTemplate>



               <asp:Timer ID="Timer1" runat="server" Interval ="1000" OnTick ="Timer1_Tick"></asp:Timer>



               <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
                   <Columns>
                       <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
                       <asp:BoundField DataField="Name " HeaderText="Name " SortExpression="Name " />
                       <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                   </Columns>
               </asp:GridView>

               <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
           </ContentTemplate>
        </asp:UpdatePanel>
    <div>
   
    </div>
    </form>
</body>
</html>
Code File
 protected void Timer1_Tick(object sender, EventArgs e)
    {
        GridView1.DataBind();
    } 
Output
Computer Programming : How to update data, without postback
in above snap, if you change data in database table from server explorer, output affected on browser. 
© Copyright 2013 Computer Programming | All Right Reserved