-->

Saturday, March 22, 2014

Get Value by Custom View to Empty Controller in VS 2013: MVC 4

In earlier article we have added an empty controller with an action named GetValues in Visual Studio 2013. That action is of type HttpGet and return a simple view having a textbox control only. In this article we will access that value in the same controller with of course an HttpPost type of action.

The first thing is to create an HttpPost type of action having the same name to access the value from the view. Write the following code in the Empty controller just below the previously written GetValues action that is of type HttpGet.

[HttpPost]
public ActionResult GetValues(string username)
{
ViewBag.insertedValue = username;
return View();
}
Check out the parameter name of this action, it have the same spelling our textbox have. I have just save that value in the ViewBag and return the same view. Now in the view page I have added a simple submit button the section to display the value of this ViewBag. Here is the code of view page:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
        </div>
        <input type="submit" value="Send" />
        <div>
            Accessed value: @ViewBag.insertedValue
        </div>
    </div>
}
Remaining code is as same as in earlier article, the change is only the submit button and a section to display the value. Now run this MVC application and write http://localhost:portNo/Empty/GetValues in the address bar of the browser and press enter.

Get Value by Custom View to Empty Controller in VS 2013: MVC 4

At the last of image Accessed value:  is blank initially. Write anything in the textbox (here DotProgramming) and click on the Send button. It will go to the HttpPost action of this view i.e. written above with the value inserted and then save that value in ViewBag. Remember, we have return the view in post action so it will come back with the value inserted and write on the view page as shown.

Get Value by Custom View to Empty Controller in VS 2013: MVC 4

The algorithms using recursion Ascending and Descending order array

We can rewrite both the algorithms using recursion:

Ascending order array:

BINSEARCH(arr, FIRST, LAST, key)
[‘arr’ is one-dimensional array of size ‘n’, key is element to search ]
[‘arr’ elements are stored in ascending order]
[FIRST is lower bound and LAST is upper bound of the array]
MID <--INTEGER((FIRST+LAST)/2)
If (arr[MID] = key) Then:
 Return 1[1for TRUE, successful search]
Else:
   If FIRST > LAST Then:
     BINSEARCH(arr, FIRST, MID-1, key)
    Else:
      BINSEARCH(arr, FIRST, MID+1, LAST,  key)
     [End of If]
  [End of If]
[End of if]
Exit.

Descending order array:

BINSEARCH(arr, FIRST, LAST, key)
[‘arr’ elements are stored in descending order]
[FIRST is lower bound and LAST is upper bound of the array]
MID <-- INTEGER((FIRST+LAST)/2)
If(arr[MID]= key) Then:
  Return 1[1 for TRUE, successful search]
Else:
  If FIRST>LAST Then:
    Return 0[0 for FALSE, unsuccessful search]
  Else:
     If arr[mid] > key Then:
        BINSEARCH(arr, MID+1,LAST,key)
      Else:
        BINSEARCH(arr, FIRST, MID+1, key)
       [End of If]
   [End of If]
[End of If]
Exit.
 

Create Custom View using an Empty Controller in VS 2013: MVC 4

In MVC4 application with Visual Studio 2013, we have added a student controller with its default CRUD actions/views including list, create, edit and details. In this article we will add an empty controller and create a new action with its associated view (having a form in it).

On the controller folder right click and add a new controller. After clicking on Add an Add Controller window will open opting some options shown in the following image:

Create Custom View using an Empty Controller in VS 2013: MVC 4

The first input is the name of controller, write Empty and in the Template option select Empty MVC
Controller and click on “Add”. It will add a new empty controller with a single action i.e. Index having a single line of code, delete this code and create a new action with that single line of code as shown:

public class EmptyController : Controller
{
public ActionResult GetValues()
{
return View();
}
}
Right click on GetValues text and select Add View option, it will show an Add View window with some of the options to be selected by the programmer. Just select only master file if not selected and leave all remaining options as they are. Those options are not usable now, we will discuss them later.

Create Custom View using an Empty Controller in VS 2013: MVC 4

Click on Add and a view having a piece of code containing title message, layout and a header text also. Leave that code and write the following code in that view:

@using (Html.BeginForm())
{
    <div>
        <div>Name: </div>
        <div>
            @Html.TextBox("username")
        </div>
    </div>
}
This code will create a single textbox having the id "username" that will be used to access the value entered in this textbox. There is no button on this form to submit the value of this textbox that will be created in next article. As I have discussed earlier that an action have two types HttpGet and HttpPost. So the above action GetValues is an HttpGet type of method because of single returning view code.

The post method is used to get the inputted values of this view and use them for further process. Through this get method programmer can also send some value to the view just like the title of the view. The title of the view is GetValues as written on the first line of the .cshtml code. Programmer can easily change this title by either sending the title by the Get view or by simple edit this line of code. Now run this MVC application and write http://localhost:portNo/Empty/GetValues in the address bar of the browser and press enter.

Create Custom View using an Empty Controller in VS 2013: MVC 4

Now we will create a submit button on this view and access the value of this textbox in the HttpPost method of the same action in further article.

Algorithm for binary search for data structure in'C'

Algorithm for binary search:

BINSEARCH (arr, n, key)
[‘arr’ elements are stored in ascending order]
success <--FALSE; FIRST<--1; LAST<--n
MID <--INTEGER((FIRST+LAST)/2)
Repeat While (FIRST <= LAST)
  If(arr[MID] = key) Then:
     success <-- TRUE; Return success
   Else:
     If arr[MID] > key Then:
       LAST <-- MID - 1
    Else:
      FIRST <-- MID + 1
    [End of If]
  [End of If]
[End of While]
Return success
Exit.
               In this algorithm when the while loop terminates the variable ‘success’ assigned with FALSE is returned. When the search is successful the algorithm terminates by returning the value of variable ‘success’ as TRUE. So we can check easily from the algorithm that the search unsuccessful when the variable value FIRST is greater then that of LAST.

Friday, March 21, 2014

How to check rank of array in ASP.NET , C#

Take an simple web form into your project. Add some control like , Button and label control on it. DOTNET IDE provides the source after adding control on design window.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>   
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="Arraydimansion" />   
    </div>
    <p>   
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>   
    </p>
    </form>
</body>
</html>

 Now, Add event handler code in business logic code. Take one, two and three dimensional array with different types. Now, bind label control from rank property of array.

Business Logic code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{   
    protected void Button1_Click(object sender, EventArgs e)
    {
        string[] Onedimensions = new string[2];
        string[,] Twodimensions = new string[2, 5];
        string[, ,] Threedimansions = new string[1, 1, 1];
   
        int[,] intArray = new int[2, 3];
        int[, ,] intArray2 = new int[1, 1, 1];
        int[][] intArray3 = new int[5][];
 
        Label1.Text = "size of dimensions of the Onedimensions: " + Onedimensions.Rank.ToString();
        Label1.Text += "<br />size of dimensions of the Twodimensions: " + Twodimensions.Rank.ToString();
        Label1.Text += "<br />size of dimensions of the Threedimansions :  " + Threedimansions.Rank.ToString();
     
        Label1.Text += "<br /><br />size of dimensions of the intArray: " + Onedimensions.Rank.ToString();
        Label1.Text += "<br />size of dimensions of the intArray2: " +Twodimensions.Rank.ToString();
        Label1.Text += "<br />size of dimensions of the intArray3: " + Threedimansions.Rank.ToString();
       
    }
}

Code generate the following output


How to check rank of array in ASP.NET , C#

Binary search applied to one-dimensional array

Binary search applied to one-dimensional array

Before reading this section find out the meaning of queue in any English dictionary. You will not search the word looking page by page. No need of page by page search because you know that the words are arranged alphabetical order. Then have you reached to the word directly? I don’t think so. You skip few pages and might have reached to a page of dictionary containing the words starting with the letter ‘k’. Then you further skip the next few pages not previous ones because you know the letter ‘q’ comes after ‘k’. Now if you reach to the page of letter ‘r’, you skip few previous pages, then finally reach to the page containing word ‘queue’.
      As we have already seen that binary search can be applied to only one-dimensional sorted (arrangement of elements in ascending or descending order) or ordered array. In order to apply binary search to one dimensional array we follow a method of exact division of array in two halves. So the name binary search. Divide the array into two halves to get the middle element. compare the key to be searched with the middle element, if both are equal, the search is successful. Otherwise repeat the application of process either to the left half or to the right half depending on the possible placement of element in the array.
          To find the middle element of the array for the first time, we can use the first index and the last index of the array. find out the middle element’s index by finding the sum of first and last index and dividing the sum by 2. Compare the key with the middle element. If both are equal search is successful in the first comparison otherwise the key may be greater than or less than the middle element. 
If key is greater than the middle element, change the first index as middle index plus 1 and keeping the last index as it is in case of first step repeat the process. 
If key is less than middle element, change the last index as middle index minus 1 keeping the first index as it is in case of first step repeat the process.
The process of finding out the middle index and comparison of key with the middle element must be stopped if the first index is greater than the last index and in that case the search is unsuccessful.
        So, when binary search is applied for one-dimensional array we consider the lower bound as first index and upper bound as last index. Usually the lower bound of an array is 1 and the upper bound of array is N, the size of the array. In case of C language the lower bound of array is 0 and the upper bound of the array is N-1, where N is the size of the array. so take two variables FIRST and LAST and initialize FIRST variable with lower bound value and LAST variable with upper bound value. Take another variable MID and initialize that variable with integer part of [(FIRST+LAST)/2].Compare the given key with MID index element of the array.

 Three possibilities arise from the comparison, MID indexed element may be:

=                   report search successful 
 <                 go for the left half of the array by changing the value of variable LAST as MID-1.Keep the                            value of variable first unchanged. Find out the MID value again and repeat the process of                              comparison.
<                  go for the right half of the array by changing the value of variable FIRST as MID+1. Keep the                       value of variable LAST unchanged. Find out the MID value again and repeat the process of                           comparison.
               The process of comparison terminates when the search is successful or the value of variable FIRST is greater than that of LAST (in that case obviously the search is unsuccessful).
              The above case of binary search is based on the assumption of array elements stored in the ascending order. If the array elements stored in descending order then, the change in the values of variables LAST and FIRST is reversed. 

Thursday, March 20, 2014

Change header Row color of GridView in ASP.NET

Change header row font color using property bar

If you want to change color of the header row use property bar and change it. After changing , a new code will be added with GridView like <Headerstyle> check given below code.
Example of Font Forecolor of Gridview in asp.net


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataKeyNames="Sno" DataSourceID="SqlDataSource1">
        <Columns>
            <asp:BoundField DataField="Sno" HeaderText="Sno" InsertVisible="False" 
                ReadOnly="True" SortExpression="Sno" />
            <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
            <asp:BoundField DataField="address" HeaderText="address" 
                SortExpression="address" />
            <asp:BoundField DataField="contactno" HeaderText="contactno" 
                SortExpression="contactno" />
        </Columns>

  <HeaderStyle ForeColor="#660066" />

    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        DeleteCommand="DELETE FROM [userdataTable] WHERE [Sno] = @Sno" 
        InsertCommand="INSERT INTO [userdataTable] ([name], [address], [contactno]) VALUES (@name, @address, @contactno)" 
        SelectCommand="SELECT * FROM [userdataTable]" 
        UpdateCommand="UPDATE [userdataTable] SET [name] = @name, [address] = @address, [contactno] = @contactno WHERE [Sno] = @Sno">
        <DeleteParameters>
            <asp:Parameter Name="Sno" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="name" Type="String" />
            <asp:Parameter Name="address" Type="String" />
            <asp:Parameter Name="contactno" Type="Int32" />
            <asp:Parameter Name="Sno" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <div>
    
   </div>
    </form>
</body>
</html>

Code output:

Change header Row color of GridView in ASP.NET
© Copyright 2013 Computer Programming | All Right Reserved