Tuesday, 18 February 2014

Creating a simple model using MVC

In this section we will create a simple customer model, flourish the same with
some data and display the same in a view.


Step1:- Create a simple class file

The first step is to create a simple customer model which is nothing but a
class with 3 properties code, name and amount. Create a simple MVC project,
right click on the model folder and click on add new item as shown in the below
figure.
14
From the templates select a simple class and name it as customer.
15 

Create the class with 3 properties as shown in the below the code snippet.

public class Customer
{
private string _Code;
private string _Name;
private double _Amount;

public string Code
{
set
{
_Code = value;
}
get
{
return _Code;
}
}

public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}

public double Amount
{
set
{
_Amount = value;
}
get 
{
return _Amount;
}
}
}


Step2:- Define the controller with action

The next step is to add the controller and create a simple action display
customer as shown in the below code snippet. Import the model namespace in the
controller class. In the action we created the object of the customer class,
flourished with some data and passed the same to a view named as “DisplayCustomer”

public class CustomerController : Controller
{
…..
….
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer);
}
}

Step3:- Create strongly typed view using the class

We need to now join the points of MVC by creating views. So right click on the
view folder and click add view. You should see a drop down as shown in the below
figure. Give a view name, check create a strongly typed view and bind this view
to the customer class using the dropdown as shown in the below figure.



16
 
The advantage of creating a strong typed view is you can now get the
properties of class in the view by typing the model and “.” as shown in the
below figure.



17



Below is the view code which displays the customer property value. We have
also put an if condition which displays the customer as privileged customer if
above 100 and normal customer if below 100.

<body>
<div>
The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>
This is a priveleged customer
<% } else{ %>
This is a normal customer
<%} %>

</div>
</body>





Step 4 :- Run your application 

Now the “D” thing, hit cntrl + f5 and you will get the output.

18
















Passing Data between controllers and views

The controller gets the first hit and loads the model. Most of the time we
would like to pass the model to the view for display purpose.

As an ASP.NET developer your choice would be to use session variables, view
state or some other ASP.NET session management object.

The problem with using ASP.NET session or view state object is the scope.
ASP.NET session objects have session scope and view state has page scope. For
MVC we would like to see scope limited to controller and the view. In other
words we would like to maintain data when the hit comes to controller and
reaches the view and after that the scope of the data should expire.

That’s where the new session management technique has been introduced in ASP.NET
MVC framework i.e. ViewData.

13 

Step1:- Create project and set view data

So the first step is to create a project and a controller. In the controller
set the viewdata variable as shown in the below code snippet and kick of the
view.

public class DisplayTimeController : Controller
{
//
// GET: /DisplayTime/

public ActionResult Index()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View();
}

}

Step 2:- Display view data in the view.

The next thing is to display data in the view by using the percentage tag. One
important point to note is the view does not have a behind code. So to display
the view we need to use the <%: tag in the aspx page as shown in the below code
snippet.

<body>
<div>
<%: ViewData["CurrentTime"] %>
</div>
</body>

 

Creating a simple Hello world ASP.NET MVC application

In this Section we will create a simple hello world program using MVC template.
So we will create a simple controller, attach the controller to simple
index.aspx page and view the display on the browser.


Step1:- Create project


Create a new project by selecting the MVC 2 empty web application template as
shown in the below figure.
6
Once you click ok, you have a readymade structure with appropriate folders where
you can add controllers, models and views.

7

Step 2:- Add controller


So let’s go and add a new controller as shown in the below figure.
8

Once you add the new controller you should see some kind of code snippet as
shown in the below snippet.

public class Default1Controller : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
return View();
}
}

Step 3:- Add View


Now that we have the controller we need to go and add the view. So click on
the Index function which is present in the control and click on add view menu as
shown in the below figure.











9

The add view pops up a modal box to enter view name which will be invoked
when this controller is called as shown in the figure below. For now keep the
view name same as the controller name and also uncheck the master page check
box.

10 

Once you click on the ok button of the view, you should see a simple ASPX
page with the below HTML code snippet. In the below HTML code snippet I have
added “This is my first MVC application”.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
This is my first MVC application
</div>
</body>
</html>

Step 4:- Run the application


If you do a CNTRL + F5 you should see a error as shown in the below figure.
This error is obvious because we have not invoked the appropriate controller /
action.




11
 

If you append the proper controller on the URL you should be able to see the
proper view.

12






ASP.NET MVC

Here i will show you an example of ASP.Net MVC Hello World Application.

ASP.Net MVC Hello World tutorial:

Step 1: Open Visual Studio & Click on File - New Project

Step 2: In the New Project Dialog box under Visual Studio Installed templates - Select ASP.Net MVC Web Application & Name the project as HelloWorldMVC - You can create applications using Visual Basic or Visual C#. For now, Select Visual C# and Click on OK 


MVC HelloWorld1





























































Step 3: In the Next "Create unit Test project" dialog box Select - "No" for not creating a unit test project.

MVC HelloWorld2






Step 4: Now you will find one demo module is added in Solution Explorer as shown in figure.
MVC HelloWorld3

Step 5: Now Click on the  Debug (Press F5) button to Run the project. Now you will find a demo site as shown in figure. [Note we have modified the text of About Us through About.aspx]. This site by default have two link which are Home & About and also it has Login and register page which you can modify according to your need.
MVC HelloWorld4






Monday, 17 February 2014

Set MaxLength for Multiline TextBox in ASP.Net using jQuery

By default the MaxLength property does not work for Multiline TextBox and hence I have created a jQuery Plugin which sets MaxLength for ASP.Net Multiline TextBox and also displays the character count as text is typed.
 
Implementing the jQuery MaxLength Plugin for ASP.Net MultiLine TextBox (TextArea)
Below you will notice the implementation of the jQuery MaxLength plugin. The jQuery MaxLength plugin has the following required and optional parameters
1. MaxLength (required) – Integer value indicating the Maximum character length limit.
2. CharacterCountControl (optional) – By default the plugin will display character count below the TextArea, but user has option to explicitly specify the Character Count Control.
Note: The character count control can only HTML SPAN or DIV.
3. DisplayCharacterCount (optional) – Default true. If set to false the Character counting will be disabled.
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">script>
    <script type="text/javascript" src="MaxLength.min.js">script>
    <script type="text/javascript">
        $(function () {
            //Normal Configuration
            $("[id*=TextBox1]").MaxLength({ MaxLength: 10 });
 
            //Specifying the Character Count control explicitly
            $("[id*=TextBox2]").MaxLength(
            {
                MaxLength: 15,
                CharacterCountControl: $('#counter')
            });
 
            //Disable Character Count
            $("[id*=TextBox3]").MaxLength(
            {
                MaxLength: 20,
                DisplayCharacterCount: false
            });
        });
    script>
head>
<body>
    <form id="form1" runat="server">
    <div id="counter">
    div>
    <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Width="300" Height="100"
        Text="Mudassar Khan">asp:TextBox>
    <br />
    <br />
    <asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine" Width="300" Height="100">asp:TextBox>
    <br />
    <br />
    <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Width="300" Height="100">asp:TextBox>
    form>
body>
html>

Print Specific part of Web page in ASP.NET

In this short article I will explain how to print specific (particular) part of web page in ASP.Net using C# and VB.Net.

The idea is to place the contents to be printed inside an ASP.Net Panel control and then print the contents of the Panel control.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type = "text/javascript">
        function PrintPanel() {
            var panel = document.getElementById("<%=pnlContents.ClientID %>");
            var printWindow = window.open('', '', 'height=400,width=800');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write('</head><body >');
            printWindow.document.write(panel.innerHTML);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            setTimeout(function () {
                printWindow.print();
            }, 500);
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat = "server">
    <asp:Panel id="pnlContents" runat = "server">
        <span style="font-size: 10pt; font-weight:bold; font-family: Arial">Hello,
            <br />
            This is <span style="color: #18B5F0">Mudassar Khan</span>.<br />
            Hoping that you are enjoying my articles!</span>
    </asp:Panel>
    <br />
    <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick = "return PrintPanel();" />
    </form>
</body>
</html>
In the above HTML Markup I have an ASP.Net Panel control pnlContents whose contents needs to be printed and an ASP.Net Button btnPrint which has an OnClientClick event which will call the JavaScript method PrintPanel() to print the contents of the Panel.