ASP.NET MVC Example – Part 3

Hope you have read and understood Part-1 and Part-2 of this article, in this part we are actually dealing with MVC architecture of ASP.NET, as we have already created middle tier which is Model in MVC now we are going to implement View part of the MVC.

We will create a Index page which will have link to Create Student link and list all the students with edit option, once we develop the page, output will look like below

image

Now we will start modifying HomeController.cs which is default controller added when you create a ASP.NET MVC application. Modify Index action to return list of students which are already present in the database, just create a object of StudentMiddleware class and call getAllStudentDetails to get all students details and add the result to View.

image

We will now create a View page for Index action, right click on Index and create a Index page, to display student details we will make this index view page strongly type to make it strongly typed create view and extend it from Student class like below

you can edit index.aspx page header like below

Inherits=”System.Web.Mvc.ViewPage<IEnumerable<StudentsMiddleware.Student>>”

or in index.aspx.cs modify like below

Public Class Index : ViewPage<IEnumerable<StudentsMiddleware.Student>> once you have done this now we display the data on the page, open Index.aspx and modify the html like below.

image

In the code above we are looping through the ViewData.Model and displaying records in a table, as we have returned the List<Student> class to ViewData in the Index action we are now able to read the records this the advantage of declaring the Strongly typed views.

Now we will create a Create Student Action, in the above screen shot you might have already observed that we have created a link with Create a Student now we will create action to that link

 

image 

Add 2 Create function shown in above screen shot in HomeController.cs, let me explain why we need 2 Create function here, you might have observed that we are differentiating 2 Create method with AcceptVerbs tag, this tag will determine the request method GET/POST and calls corresponding action.

The GET Create action will simply return to corresponding View and POST Create Action will take the data entered in the View and Inserts into database using our StudentMiddleware class’s InsertStudentDetails

 

Now we need a create View to the Action so just right click on the Action and create a View and modify Create.aspx page like below screen shot

image

 

Here I have used Html object which has some defined methods which will give us flexibility to create HTML controls easy. After entering the data we will submit this form to POST Create Action.

Now we will implement update function for student now add new controller save it as StudentController.cs and add following 2 functions

 

image

Now right click and a add DisplayStudent.aspx view to display particular student details and a update button to update the details. please modify the DisplayStudent.aspx as shown in below screenshot.

image

Now we are done with our example go ahead and build and run.

 

Hope this help, don’t forget give your input to this article

 

SatishKumar J

Microsoft MVP(ASP.NET)

Displaying Multi Language Data on an ASP.NET web page

Handling multi language data is very much important these days; localization of your web page can increase the visitors.

 

 Here in this article I am trying to explain how to deal with the multi language data, here I am trying to explain how you can insert data into SQL Server database and retrieve the data from SQL Server data base and display on the web page.

 

Create a Database namely MultiLangaugeDB and create a table MultiLanguageData

 

USE [MultiLangaugeDB]

GO

/****** Object:  Table [dbo].[MultiLanguageData]    Script Date: 02/19/2009 09:34:36 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

SET ANSI_PADDING ON

GO

CREATE TABLE [dbo].[MultiLanguageData](

            [Title] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

            [Description] [binary](1000) NULL

) ON [PRIMARY]

GO

SET ANSI_PADDING OFF

 

To insert data into this table we need write a stored procedure, why because if you try to insert data directly from web page, then you will loose the data while creating a SQL insert statement, so we create a stored procedure to insert data, create following stored procedure in the MultiLangaugeDB

 

USE [MultiLangaugeDB]

GO

/****** Object:  StoredProcedure [dbo].[InsertMultiLanguageData]    Script Date: 02/19/2009 09:36:58 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

 

CREATE PROCEDURE [dbo].[InsertMultiLanguageData]

            – Add the parameters for the stored procedure here

            @Title nvarchar(50),

            @Desc binary(1000)

AS

BEGIN

            SET NOCOUNT ON;

            Insert into MultiLanguageData Values (@Title, @Desc)

END

 

Now we are ready with back end stuff, now lets go and create a web page to insert data.

Create a new web application

On the Default.aspx page add 2 text boxes with and 2 buttons

Fist text box will be used for Title and second text box is used to enter actual multi language data

Name the Button Insert, Displays respectively

Double click on Insert button in the design and add following code in code behind

insert 

 

Here we need to understand the we are converting data into bytes and storing into data base that is why we are have taken our Decription Field in the database table as binary, so that our data will not be lost

 

Now to diplay we need to convert binary data back into string format, that will be using Encoding.Unicode.GetString this will take binary data and convert that data into perticualar language data

 

Just doule click on diplay button in design and add following code in code behind

display 

Now we are ready with our program, just Build, Run and Test

output

Hope this Helps

 

SatishKumar J

MVP (ASP.NET)

ListView Groups Example

ListView Groups Example:

This example reads a directory in windows and list out all files in groups, for example I have .doc and .xls etc files in my directory it creates 2 groups and add files according to groups

• Create a windows application
• Drag and drop ListView Control on to the form
• Drag and drop FolderBrowseDialog on to the components panel
• Drag and drop a Button on to the form

desing
• Double click on the button and add following code

code

Build and Run.

Hope this helps.

SatishKumar J
MVP (ASP.NET)

Tags: ListView Groups Example, C#, .NET

Generating Auto Number

This code snippet will generate a Auto Number with your format, I tried generalize as much as possible, this function allows to decide how many digits you want have and you have a Pre Fix to your Auto Number.

public string GenerateAutoNumber(string preFix, int numberOfDigits, string currentNumber)

{

//preFix : it can be any string which you want to have starting of your number

//numberOfDigits: this specifies how many digits you have in your AutoNumber

//currentNumber: this is current Number if pass current Number it will generate next number for example

// if your number is SAT00001 then function will return SAT00002

if (currentNumber == "")

{

currentNumber = preFix + currentNumber.PadLeft(numberOfDigits, ’0′);

}

double autoNumber = Convert.ToDouble("2" + currentNumber.Substring(preFix.Length, currentNumber.Length – (preFix.Length)));

string strNumber = (autoNumber + 1).ToString();

return preFix + strNumber.Substring(1, strNumber.Length – 1);

}

 

Testing Above Function

//Initially Generating Number

String currentNumber = GenerateAutoNumber("SAT", 5 , "");

Response.Write(currentNumber); // Ouput will be SAT00001

//Generating auto number based on currentNumber

Response.Write(GenerateAutoNumber("SAT", 5, currentNumber)); // Ouput will be SAT00002

 

Satish Kumar MVP (ASP.NET)

ASP.NET MVC Example – Part 2

I hope you read part -1 of this example and understand a basic and high level of over view of MVC architecture, in this part I will be talking above the Model (Business logic Layer)

Part – 1: Creating basic MVC project

Part – 2: Creating Business Logic layer

Part – 3: Interacting with Model

This is general concept not specific to MVC or any architecture; I am going to create a class which handles all the manipulation of the Student Database.

Create a new database in SQL Server and name it as Students, and Create a Table Student with following fields.

StudentID – Int (Identity on)

StudentName – nvarchar(50)

StudentAddress – nvarchar(50)

StudentCity – nvarchar(50)

StudentClass – nvarchar(50)

Once you have done with creating a sample students database, now open our StudnetMVCExample project and right click on the Model folder in solution explorer and Add New Item and select a class file, and name it as StudentsMiddleware click Ok.

Now create a getStudentDetails function as you see in below screen shot, and also don’t forget to declare a private variable strConnectionString

getstudent

 

Add a function to get all students

 

getAllStudent

 

Add a function to Insert Student Details

insertstudent

Add a function to Update Student Details

updatestudent

As we are dealing with student, it is better and simple to have student class which will hold details of a single Student, create a student class in same file after StudentsMiddleWare class like shown in below Screen shot

studentclass

Now we are ready with our middle ware logic, so we can continue with our MVC web application.

Very soon I will be posting next part of this example in which I will be explaining how to interact with Model in MVC web application.

Happy Coding

Regards,

Satish.

ASP.NET MVC Example – Part 1

I am starting an example on ASP.NET MVC; I am planning to have 3 parts of this example so that it will be easy for understanding.
Structure of the example:

Part – 1: Creating basic MVC project

Part – 2: Creating Business Logic layer

Part – 3: Interacting with Model

 

 

To create an ASP.NET MVC web application, go to New Project and select C# / VB.NET any of your language preference projects, when select Web projects you will see ASP.NET MVC Web Project template at right window select it, and change the project name to StudentMVCExample and Click Ok.

createproject

 

After click ok there will be a dialog box asking “do you want to create a testing project?” say no.

 

Once project is created you will see many files and some folder are added by default, I will be explaining those files bit later.

 

Let us understand how URL routing works in ASP.NET MVC web application, if you open global.asax file,

globalasax

 

Normally in MVC application you will not request for an .aspx page but you will request for an Action, this action is identified by a Controller class and executes the action provides output in View; MVC application URL pattern will be http://www.YourWebSite.com/Controller/Action/Id

If you observe in above screen, controller is set to Home Action is set to Index and Id is set to empty string, this default routing set by Visual Studio for our convenience.

 

Let me explain what is Controller and View here.

homecontroller

 

Controller is a class which takes requests from the user, Controllers are invoked by MVC framework reading the URL, this controller class will have all the Actions listed in them, for example Index Action, each Action in the controller class will have View in the View Section as you can see the above screen shot.

 

Now just press F5 to run the application, as of now we have not done any thing in our project we will see a default home page

 

home_run

If you observe the URL of the page, http://localhost:34343/ we have not specified any controller or action so it took from default routing and executes Home Controllers Index Action displays Index View

 

Now click on About button the right side and observer the URL

 

about_run

You can see Home/About, this means it executed Home Controllers About Action and displayed the About View.

 

A View is place where you will display the content received from the Action method, normally view are content pages which are linked to a master page.

 

I hope this will give a high level over view of the basic ASP.NET MVC web application; I will be posting how to handle with Model (business logic layer) in MVC architecture in next part of this article.

 

Happy Coding

 

Cheers,

Satish.

ASP.NET MVC

ASP.NET is providing a powerful component MVC in ASP.NET3.5, MVC stands for model view controller and it is a design pattern used for applications, it is very flexible pattern using which you can make very flexible and independent components.

 

Basically in ASP.NET MVC applications we have a controller which will respond to a request, however in traditional web page we will have a page life cycle and request will go through all the stages, in MVC a controller will identifies a request and after executing business logic it will redirect to a view page with the requested data, this also follows maximum of page lifecycle stages but you can separate the model and view and build independent components.

 

MVC URL look like http://yourwebsite/Customers/SearchCustomer/SomeCustName

 

In above URL Customers is the Controller and SearchCustomer is method which will search customers based on SomeCustName, and controller will send searched customers data to its View

 

I will be posting an example soon.

 

Enjoy Coding

 

Cheers,

Satish.