Monday, December 22, 2014

How to upload a file in MVC 4.0 Razor

In this tutorial I will show you how to upload a files in ASP.NET MVC 4.0. So how to do this?? Lets get start. Create a new MVC 4.0 application and add a new controller, name it as HomeController. We will use Index ActionMethod to write the code to upload the file.

We need two ActionMethod named Index, one is for HttpGet and another for HttpPost. Within the HttpGet ActionMethod we don't need to write anything.

Lets create the View first. To create the View right click on the ActionMethod Index and click on the Add View  option.

In the View write down the code.

    ViewBag.Title = "Upload file";

<h2>Upload File</h2>
<h3 style="color: green">@ViewBag.Message</h3>
@using (Html.BeginForm("Index", "Home", FormMethod.Post
            , new { enctype = "multipart/form-data" }))

    <input type="file" id="fileToUpload" name="file" />
    <span class="field-validation-error" id="spanfile"></span>

    <input type="submit" id="btnSubmit" value="Upload" />

Here we have taken a simple HTML file up loader and a submit button. Within the form we are calling the ActionMethod Index, which is present in HomeController. A ValidationSummary to show all validation message.

Now get back to the ActionMethod. Within the Index ActionMethod (HttpPost) write down the code.

public ActionResult Index(HttpPostedFileBase file)
      if (ModelState.IsValid)
           if (file == null)
              ModelState.AddModelError("File""Please Upload Your file");
           else if (file.ContentLength > 0)
              int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
              string[] AllowedFileExtensions = new string[] { ".jpg"".gif"".png"".pdf" };
           if (!AllowedFileExtensions.Contains
                 ModelState.AddModelError("File""Please file of type: " + string.Join(", ", AllowedFileExtensions));
           else if (file.ContentLength > MaxContentLength)
                 ModelState.AddModelError("File""Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                 var fileName = Path.GetFileName(file.FileName);
                 var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                 ViewBag.Message = "File uploaded successfully. File path :   ~/Upload/"+fileName;
     return View();

Before run this project don't forget to create a Upload folder within root directory, otherwise you will get an error.

HttpPostedFileBase file getting the file which you are uploading.

file.ContentLength : Size of the file
file.FileName : file name with extension

Now run your project and enjoying your uploading.

Download the full source code here.

Tuesday, December 16, 2014

Starting with MVC4.0 Razor

In this post I will show you how to create a MVC4.0 project with Razor as a view engine. But before that lets see what is MVC.

MVC stands for Model View Controller.

  • Responsible for storing and retrieving data
  • Maintenance of states. 
  • Notification of observers of change in state.
  • Classes or references including .cs and .dll files
  • Responsible for rendering UI model.
  • User interaction (Text Box, List Box, Button, Label)
  • Normally hold .cshtml, .aspx pages to show output.
  • Responsible for responding to user input.
  • Instructing model to process the user input.
  • Make a bridge between view and model.
Every controller holds one of more than one action method(s). These action methods are calling during the execution through URL.

Like lets say the URL is localhost/Home/Index
Here Home is the controller name and Index is the ActionMethod name. Now every Action method has its own View by its name. So here a view will be stored within the View -> Home folder named Index.cshtml.
Whenever you will request for Home/Index the index.cshtml file will be shown within that View ->Home folder.

Now lets see how to start this. Open your Visual Studio 2012. It has inbuilt MVC 4.0 and MVC 3.0. If you are using Visual studio 2010 then download the MVC 4.0 set up here.

Choose  4.0 project and set your name.

The next thing you have to do to choose Razor as a View engine and don't forget to choose an Empty template.

Open your solution explorer. There will be folder named Model, Controller and View. There are two web.config in the solution. One in the root folder and another one in the View folder. The root one is the normal one to deal and the second one the file in View folder blocks the direct access of the View folder.

Normally Home is the default Controller and Index is the default action method. if you open the RouteConfig.cs file in the App_Start folder you will come to see in the method RegisterRoutes that the default controller and ActionMethod is Home and Index respectively. If you want to change it you can do easily. 

OK, so lets start with a simple program. Right click on the Controller folder and choose Create new Controller. Name it HomeController.  Open the HomeController, there will be one Index ActionMethod. Now right click on the Action Method name (Index) and you will see there are two options Add View and Go to View. As you didn't create any View previously click on the Add View option. A new window will be opened. Keep the name as it is, Set the View engine as Razor. Right now we don't have any Master page so keep the Use a layout or master page blank. Now click on the Add button and check on the View folder in the Solutions Explorer. Within a view folder there will be a folder named as your controller name Home. And within that Home controller there is index.cshtml. 

Open the index.cshtml and place any html code under <h2>Index</h2> Or you can delete it and put your code.

Hit the run button and your project will run with the all html code in your index.cshtml.

As the default ones are running we would not see any thing in the URL. It is showing some thing like http://localhost:59244/. Put http://localhost:59244/Home/Index instead of the URL right now. You will see the same result as Home controller is running and Action Method Index is calling. And you are viewing the content of index.cshtml.

Now it will be more clear if you create another Action Method in the Home Controller. So lets create another one. 

Add a View for the new controller Arka. 

Now run your project and run with localhost/Home/Arka and see whats the output. It will show the data of arka.cshtml within Home folder.

I hope the fundamental concept of the MVC architecture and how to start with this is clear to all of you. If you have any type of query just comment with your query. 

Wednesday, October 29, 2014

Show data from a database table content in MVC 4.0 razor

In this MVC tutorial post I will show you how to show a database content to a page in MVC 4.0. So for those who are not aware of MVC (Model View Controller) concept you can visit this post  as a reference.

So first create a new MVC project. Select Razor as your View engine.
Create a new database named what ever you want and add a new table named tblEmployee.Design your database as following.

And after that add an EmployeeController in the Controller folder.

And after that add an Empployee.cs in the Model folder. Add the following code into the Employee.cs.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcApplication1.Models
    public class Employee
        public int empid { get; set; }
        public string name { get; set; }
        public string dept { get; set; }


I set the Table attribute to tblEmployee as to connect the tblEmployee table with Employee class. Normally it takes the class name as the class name. But here our class name is differ from class name. So I did it.
Now add another class named EmployeeContext.cs into the Model folder again. Its is to connect the connection string in Web.Config file.
Write down the following code in the EmployeeContext.cs
using System.Data.Entity;

public class EmployeeContext : DbContext
    public DbSet employee { get; set; }

Add the connection string in the web.config as a name EmployeeContext. Now come back to EmpployeeController. Add a View of Indes Action. Doing this choose create a strongly typed view and select Employee. If Employee is not showing then do not get panic. Just build the solution once. It will show the Employee in to the drop down list to choose. Now in the Index.cshtml in View add the following code.
@using MvcApplication1.Models;
@using System.Web.Mvc;

@model IEnumerable

    ViewBag.Title = "Index";

All Employee Details

@foreach(Employee emp in @Model) { }
@emp.dept @emp.dept

In the EmployeeController write down the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
    public class EmployeeController : Controller
        public ActionResult Index()
            EmployeeContext emp = new EmployeeContext();
            List employee1 = emp.employee.ToList();

            return View(employee1); // return list of employee

Now run your project and enter the URL localhost://Employee/Index

Download the full source code here.

Sunday, October 19, 2014

How to bind a HTML Drop Down List with Web Services in ASP.NET using C#

Introduction :
In this article I will show you how to bind a Drop Down List in ASP.NET site with a web services. Before starting we need to know what is a Web Services is. Then we will know how to bind the Drop Down List with the help of that Web Service.

Web Services :
According to Tutorials point Web Services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or Web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

In web services we use WebMethod to call with parameter and to do operations. A web Services is inherited by class System.Web.Services.WebService. To check my Web Service article click here.

Starting With a Web Service : 
To start process with a Web Service create a new project, add a new Web Form. To add a new Web Service go to Add New Item. And then add a new Web Service (.asmx). Name it as you want.
 Now in the Web Form add a new HTML  Drop Down List. We will use the Web Service to bind the HTML Drop Down List.

Now we will check the following JQuery json code.
$(document).ready(function () {

function load_ddlFrom() {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "services/Bind.asmx/LoadddlForm",
                data: "{}",
                dataType: "json",
                success: function (Result) {
                    Result = Result.d;
                    $.each(Result, function (key, value) {
                error: function (Result) {

Lets check the url carefully  services/Bind.asmx/LoadddlForm 
services is the folder name where all the services are stored, I didn't use any thing before it because it is locketed in the root folder. Then Bind.asmx is the name of the web services that you are accessing. And the last one  LoadForm. It is the method name that you are invoking.  So lets check what is written in the LoadForm method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

    /// Summary description for Bind
    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    public class Bind : System.Web.Services.WebService
        public class CountryInfo
            public int Id { get; set; }
            public string Stopage { get; set; }
        public List CountryInformation { get; set; }

        public List LoadddlForm()
            CountryInfo ci = new CountryInfo();
            List CountryInformation = new List();
            DataSet ds;
            using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["booking"].ToString()))
                using (SqlCommand cmd = new SqlCommand("select Id,Stopage from tblStopageMeta where isdelete=0", con))
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))

                        ds = new DataSet();
                if (ds != null)
                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                            foreach (DataRow dr in ds.Tables[0].Rows)
                                CountryInformation.Add(new CountryInfo()
                                    Id = Convert.ToInt32(dr["Id"]),
                                    Stopage = dr["Stopage"].ToString()
            catch (Exception ex)
                throw ex;
            return CountryInformation;

Now run your project and check whether it is binding your HTML Drop Down List or not. But before that one create your database and database connection in Web.Config.

Saturday, October 4, 2014

XML and .NET

XML - Extensible Markup Language is a markup language like HTML designed for describing data as a database.

Topics to discuss :
  • Definition
  • How to write tags XML
  • Create a XML file in .NET
  • Data read from XML using ASP.NET C#
  • Edit or Update data in XML using ASP.NET C#
  • Search in XML document (Where clause)
Definition of XML :

According to Wikipedia definition of XML is.
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. 
How to write tags in XML :

As I told previously it is like HTML, a markup language, so its clear it will be written with the help of markup tags as we write HTML. Lets check a sample of XML.

     Dennis Ritchie
     Anders Hejlsberg
     Yukihiro "Matz" Matsumoto

Its looks like a database...Where data are defined in a tree structure with child and sub child. The whole XML structure are like.




Hope its clear how XML is organized to store data and perform. Now lets check next topic, write into XML using C#.

Create a XML file in .NET:

To write  a XML file in ASP.NET using C# you need to add a new namespace.

using System.Xml;

And one extra class named XmlWriter. Create an object of XmlWriter and using that object we will create a XML file and also write into it. How? Lets check the following code thoroughly.
Language[] lang= new Language[3];
employees[0] = new Employee(1, "C", "Dennis Ritchie");
employees[1] = new Employee(2, "C#", "Anders Hejlsberg");
employees[2] = new Employee(3, "Ruby", "Yukihiro "Matz" Matsumoto");

using (XmlWriter writer = XmlWriter.Create("ComLang.xml"))

    foreach Language lang1 in lang)

 writer.WriteElementString("ID", employee.Id.ToString());
 writer.WriteElementString("title", employee.FirstName);
 writer.WriteElementString("author", employee.LastName);


Read from a XML file :

After creating a XML file now its time to show the data. To view data the best one is GridView. So we will use GridView here to show the data of a XML file. You can bind a GridView with a XML file by 2 methods. First one is little bit simpler using XMLDataSource. And second one is the greatest way to do....CODING... :). No doubt I will show by second method.

So, take a GridView and on the PageLoad method write down the following code.


Now the C# code
using System.Data;

protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
private void fillGrid()
    using (DataSet ds = new DataSet())
        GridView1.DataSource = ds;

Creating and bindng is over. Its time to edit and update.

Edit or Update data in XML :

We will edit a node of the XML file used. Lets assume we will change the author of language C. So how will code? Lets check.

XmlDocument xmlDoc = new XmlDocument();

XmlNodeList nodeList = xmlDoc.SelectNodes("/computer/language");
// Chnange the author name of C to TextBox value
nodeList[0].ChildNodes[1].InnerText = txtAuhor.Text;
Response.Write("Succcessfully updated !");

nodeList[0].ChildNodes[1] means the second attribute of 1st node. A simple 2D matrix. So change it according to you attribute.
Search in XML document Now in your mind one question may arise, here Arka has shown only by a particular attribute, what about the others, if I don't know at which position C language node is present. Remember we have taken a ID attribute with out node. We will use that one to edit or update. Lets check how to to do this. This is like Where clause in XML.

XDocument document = XDocument.Load(Server.MapPath("~/ComLang.xml"));

var q = from r in document.Descendants("Language") where (int)r.Element("ID") ="+ txtID.Text +" select new {
 Title = r.Element("title").Value, Author = r.Element("author").Value };

GridView1.DataSource = q;

Now I hope its clear how to fetch a particular row of a XML document.
I thing this post will clear the whole confusions about XML and how to use XML. If you still have some confusion don't hesitate to ask me any thing. That is all for this time....Practice yourself...Happy coding :)

Friday, October 3, 2014

Print a DIV or Panel in ASP.NET C# JavaScript

Hello, today I will show you how to print a div or panel in your ASP.NET page using JavaScript and Jquery with the help of a button. Normally to print we use windows.print() option to print the whole page. but if we need to print a particular portion of a page then what to do? Solution is here.

Create a new page and add a div or ASP panel and after finishing the div add an Button. We don't need to generate the click event of the button, because we are just use it as a normal button and call JavaScript function using this. in the div write your all data, which you want to print.

Check the bellow code.

Your all data goes here....

aNow its time for dome JavaScript code to handle...

function printDiv() {
 //Get the HTML of div
 var divElements = document.getElementById("<%= PanelDiv.ClientID %>").innerHTML;
 //Get the HTML of whole page
 var oldPage = document.body.innerHTML;

 //Reset the page's HTML with div's HTML only
 document.body.innerHTML =
   "" +
   divElements + "";

 //Print Page

 //Restore orignal HTML
 document.body.innerHTML = oldPage;

Now run your project. We have use PanelDiv.ClientID because its an ASP control and its the process to access the server side controls into client side code. Hope it helps you... Happy coding ... :)

Sunday, September 21, 2014


Many of you are aware of the GTE, POST, PUT & DELETE methods in ASP.NET, these are the basic method to send the value form one Form to another Form. Lets see how these work in ASP.NET project using C#.

Using GET method you can send all the input (textbox,textarea,radio button, checkbox etc..) to another form or another page. So how to do this?

Take a HTML page and write down the following HTML codes.

In Default.aspx to get the value of these two text boxes values we have to write code in Page_Load method. Make one thing clear, in the time of GET, POST we use NAME instead of ID. So lets check what will be for get method.
protected void Page_Load(object sender, EventArgs e)
     string name = ""; string pass = "";
     if (Request.QueryString["Name"] != null && Request.QueryString["Password"] != null)
           name = Request.QueryString["Name"].ToString();
           pass = Request.QueryString["Password"].ToString();

By Request.QueryString["Name"].ToString() this one we can get the value of a field which is sending through GET method. When we hit the submit button the URL will be something like this.


Normally we don't use GET to send sensitive fields like Passwords because it shows in the URL, I used it here just for an example.

Unlike GET in the POST method we can't see the values in the URL. It sends the values internally. Basically it has 2 parts. Head and body. In the head section it holds the variable name and in the body part holds the value. We will use the same example for the POST also.
Now lets check how to get the value using POST method in C# coding.
protected void Page_Load(object sender, EventArgs e)
     string name = ""; string pass = "";
     if (Request.Form["Name"] != null && Request.Form["Password"] != null)
           name = Request.Form["Name"].ToString();
           pass = Request.Form["Password"].ToString();
use Request.Form instead of Request.QueryString to get the value from POST method. And rest of the thing is same as GET.

AJAX UpdateProgress Image(GIF) and Text in ASP.NET C#

Hi, today I will show you how use AJAX Update Progress Bar to show loading process. You can show this with a loading GIF image or any text. Its better to use an image. You can download any one, as various kinds of GIF images are available in Google or you can create your own one.

Step #1 :
So, first off all create a new project and add  a new WebForm. Add a Script Manager at the top of the form before it flushes out from you mind and get an error. After adding take an Update Panel and within that UpdatePanel take a ContentTemplate. Each and every HTML and ASP controls have to be design within the ContentTemplate if you are putting them within UpdatePanel.

Step #2:
Take a new Button and a Label to execute the operation. And then add the most important thing for this article, the UpadateProgress. You will get this tool in the tool box within AJAX Extensions.

Add the UpdateProgress into the page and change the attribute AssociatedUpdatePanelID to the UpdatePanel name. and Dynamiclayout to true.

 AssociatedUpdatePanelID="UpdatePanel1"   DynamicLayout="true"

Step #3:
Here UpdatePanel1 is the UpdatePanel, which I have taken in the project. Place the image of loading into the ProgressTemplate within UpdateProgress with normal HTML image tool or write down the Text you want to display during the process.

Lets check the code how it works.


In the project I haven't done any such work that will took so much time to show the loading message. So I am using Thread.Sleep(3000) to gain a loading time of 3 seconds. Write down the following code into the button click event.
using System.Threading;

protected void btnShow_Click(object sender, EventArgs e)
     Label1.Text = "done !";

Now it should be clear how to show a progress bar (image or text) during  loading of some thing in ASP.NET. Hope it will help you to build your project successful. Happy coding... :)

Friday, September 19, 2014

Required field and email verification using Angular JS

In my previous post I have shown how to use Angular JS in your project , now in this post I will show you how to valid a required field or an email field using Angular JS. You can do this using ASP validation process or  using JavaScript or JQuery. But in this  post I will show you how to use Angular JS to validate the HTML fields.

Username: Username is required.
Email: Email is required. Invalid email address.

Run your page into local server to validate your HTML controls using Angular JS. Happy coding .... :)

Show instantly as write into the TextBox using Angular JS

This is my first post about Angular JS. Here in this post I will show you how to show the text into <p> tag as you type into a TextBox. I will do it with the help of Angular JS. Before starting it is important to discuss some thing about Angular JS.

So, what is Angular JS actually?

  1. AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. Angular's data binding and dependency injection eliminate much of the code you currently have to write.
To add this into your project add the following line into the head section.

aNow its time to start the project. Once again I clarify the aim of the project. There will be one TextBox and one <p> tag. As you type in the TextBox the text will be show in the <p> tag. You can do this in the TextChange event in the JavaScript or JQuery. But with the help of Angular JS its a matter of one line.

Lets come how to do this.

Type Text:

ng-app : directive defines an AngularJS application.
ng-model : directive binds the value of HTML controls like input, select, textarea etc. to application data.
ng-bind : directive binds application data to the HTML view. Now run your HTML page and check it out.

Your first Angular JS page is ready to rock n roll. 

Get HTML Select(Drop Down List) value in Code Behind (C#) in ASP.NET

Sometimes its very mush important to get the value of the HTML Drop Down List, Select value from the code behind (C#). So how to get the value of a HTML control value in the code behind. A very easy thing to do.

Create a new project and add a WebForm and add a new select tag with some value. Like this

Now in the C# page write the code to get the value.
string ddl = "";
// to get the selected value
ddl = Requets.Form["ddl"].ToString();

To get the selected value the actual code is

In this way you can get the data of a HTML field from code behind (C#). With in that click event write down the following code

Thursday, September 18, 2014

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'

Sometime you found "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'." in your ASP project when you are running the project.

As a remedy of the project  "Please add a ScriptResourceMapping named jquery(case-sensitive)." What is this ? How to solve this? Very easy stuff to do.

If your project if there is no Global.asax added then add one into your project by clicking on the Add New Item. After adding this you will see there is a method Application_Start. Add the following script into that method.

    new ScriptResourceDefinition
  Path = "~/scripts/jquery-1.7.2.min.js",
  DebugPath = "~/scripts/jquery-1.7.2.min.js",
  CdnPath = "",
  CdnDebugPath = ""

Now save the Global.asax and run your project. It will run successfully. :)

Saturday, September 13, 2014

SQL Split function to split an input string

This article I am starting with a real life example. In posting an article in a blog we have to define tags (Like  C#.NET, AJAX, ASP.NET,HTML) upon the article. We usually take these tags in a TextBox with separated them by comma(,). To insert these into database we have two ways to do.

First Method using C# :

Using C# you can split the TextBox items and use a for loop to insert into the database. Code is as follow.
string []tags = txtTags.Text.Trim().Split(',');

/* With for loop */
for (int i=0;i<tags.Count ;i++)
 /* perform db query with tags[i].ToSting();

/* with foreach */
foreach (string i in tags)
  /* perform db query with i.ToSting();

Second SQL Method :

Here in the SQL we pass the whole items of TextBox into SQL function to split it and then insert these into specific table. Lets see how to do this.
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
      Item NVARCHAR(1000)
      DECLARE @StartIndex INT, @EndIndex INT
      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
            SET @Input = @Input + @Character
      WHILE CHARINDEX(@Character, @Input) > 0
            SET @EndIndex = CHARINDEX(@Character, @Input)
            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))

-- Create a temporary table to insert tags
create #tblTemp
Id identity (1,1),
tag nvarchar(50)

-- Inserting into tmpTable
insert into #tblTemp (temp) values 
SELECT Item FROM dbo.SplitText('ASP.NET,C#.NET,ADO.NET,JavaScript', ',')  
-- Seperated by Comma(,). Place any thing according to you.

Execute your SQL batch query to inserting the tags into table.

Print Page in landscape mode in HTML CSS print media

Hi every one, today's topic is to print a HTML page into landscape mode. When we print a HTML page it takes by default portrait mode. But if we have to print it into landscape mode how to do it?

To do this s following...

Create a new HTML page and put the above code in head section.
Page 1
Page 2
Page 3
Page 4

Try it yours.

Output :
Landscape Print

Printing Page size in A4 using CSS Paged media

When ever you are sizing a div in your HTML page you size it with width and height in style sheet. Suppose whenever you have to print that div into A4 page size will it work properly? Not necessary it will print in the same size. So what to do? Simple put the div size into A4. But question is HOW? Let me clarify you.

Create a new HTML page and write create a div within body.

Page 1
Page 2
Page 3
Page 4
Now check the CSS once.
    body {
        margin: 0;
        padding: 0;
        background-color: #FAFAFA;
        font: 12pt;
    * {
        box-sizing: border-box;
        -moz-box-sizing: border-box;
    .page {
        width: 21cm;
        min-height: 29.7cm;
        padding: 2cm;
        margin: 1cm auto;
        border: 1px #000 solid;
        border-radius: 5px;
        background: white;
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    .subpage {
        padding: 1cm;
        border: 5px black solid;
        height: 237mm;
        outline: 2cm #000 solid;
    @page {
        size: A4;
        margin: 0;
    @media print {
        .page {
            margin: 0;
            border: initial;
            border-radius: initial;
            width: initial;
            min-height: initial;
            box-shadow: initial;
            background: initial;
            page-break-after: always;

View your page into browser and press Ctrl + P to check whether its diving the page according the size of A4 or not. I am sure it will work 100%. 

Friday, September 12, 2014

Ajax Control toolkit ModalPopUp in ASP.NET C#

Here I am going to show how to create a modal pop up using AJAX control toolkit in ASP.NET and C#. Before I have show how to create a pop up using JQuery and CSS, but now its pure asp. For this you need to add AJAX Control toolkit into your project. You can download as per your version of .NET (3.5,4.0,4.5).
After downloading create a project and add the reference of the AJAX Control Toolkit into your project.

Now your visual studio is ready to begin with AJAX Control Toolkit. Add a new Web Form. In the tool Box you will get the control ModalPopupExtender within AJAX Control Toolkit.

Lets first see how to set a ModalPopup to show any message. Check the following code.

AJAX Modal Popup

Here is the content which you wan to show

Run this example and on the button click you will get a pop up showing in your browser.

Lets move to an example where you will get an message showing with data from back end. Add another page and check following code.

In the CS page write down the following code.
protected void btnClick_Click(object sender, EventArgs e)
 /* get data from DB */
 lblusername.Text = TextBox1.Text;

Output :
Direct Message showing

Message from code behind

I hope its clear how to create popup and how to show message or show message from code behind. For further download the full source code here.

Polymorphism(Method Overloading and Overriding) in C#

Today's topic is a old one. Maximum among you are familiar with this topic. I am talking about one of the OOPs(Object Oriented Programming) feature polymorphism. In your college life you had come to know about polymorphism, but today I will discuss about this very known topic with the help of C#. As usual I have taken Find Area as an example like you did in your college.

Lets come to the point straight way.  Polymorphism has two parts.
  1. Method Overloading
  2. Method Overriding
Method Overloading :
So, lets start with the Method Overloading. Create a new project and take two textboxes, one button and one label for showing result.  Before starting one question came into the mind.. What actually method overloading is. Before this let me say about one very important issue about methods or function. A method name depends not only its name but also on its return type and argument. If you keep the name same and create a new method with a different return type and arguments it will act as a different method. This is  Method overloading. Calling the particular method, which has named more than one, but with distinct return type and argument.

In calculating area of a rectangle and a circle, the only difference is no of argument. In the first case you have to provide two argument(length and breath) but in the case of circle only one(radius) is enough to get the area. So, we will create two methods named FindArea() with 2 different argument. Lets check the following example.

/// For circle
private Double FindArea(string r)
     return 22 / 7 * Math.Pow(Convert.ToInt32(r),2);

/// For rectangle
private int FindArea(string l, string b)
     return (Convert.ToInt32(l) * Convert.ToInt32(b));

Your methods are ready. Now you have to call these. For this generate click event of the button, and write down the following code.
protected void btnSubmit_Click(object sender, EventArgs e)
 /* For rectangle */
 if (txt1.Text != "" && txt2.Text != "")
  lblArea.Text =  FindArea(txt1.Text.Trim(), 
 /* for circle */
 else if (txt1.Text != "" && txt2.Text == "")
  lblArea.Text = FindArea(txt1.Text.Trim()).ToString();
  lblArea.Text = "Fill any of the two input box !";

I hope it is clear to you what is method overloading and how its work. Now lets move to method overriding.

Method Overriding :

Not like method overloading its about inheritance. Before starting discussing about the inheritance is important. Inheritance is one of the property of OPPs programming concept, to get the all properties and methods of a parent class to the child class. Like all of your parents property is yours, because you are inheriting your parents.

So here we have taken two classes, parent.cs and child.cs and child.cs is inheriting parent.cs. So what ever variables or methods are declare in the parent.cs is accessible for child.cs.

We have declare abc() method in both class and creating  an object of child class. Using this object we are calling the abc() method. Now in the child class there are two abc() methods are present. One is its own and another is inherited from parent class. So, which method will be called? Answer is child class one. The child class method will override the parent class method to execute. Lets check the code once.
public class parent
 public parent() { }

 public string abc()
  return "parent -> abc";

public class child : parent
 public child() { }

 public string abc()
  return "child -> abc";

Now call the method.

child obj = new child();

Output : child -> abc

Hope so both are clear for you, for your help you can download the full source code here.

Popular Posts