Click here to Skip to main content
15,886,578 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET MVC Basics in 60 Minutes

Rate me:
Please Sign up or sign in to vote.
4.10/5 (8 votes)
20 Apr 2015CPOL4 min read 26.6K   20   9
This tip can be helpful in learning MVC quickly, without undertaking any service based architecture.

Introduction

This tip details out the steps to build MVC application quickly using the best & quick practices that are provided by ASP.NET MVC. In the application, I am building a School Management website with some simple actions of add/view/edit/delete the Student information. 

I have used Visual Studio 2013 along with Update 4, SQL Server 2012 to build this application.

Using the Code

  1. Start with a New Project - Select ‘ASP.NET Web Application’, name it as SchoolManagement, as given below:

  2. Select ‘Single Page Application’, as given below:

  3. Open SQL Server Management Studio and create a new database – ‘SchoolManagement’. Use the following script for creating a Student table:
    SQL
    USE [SchoolManagement]
    GO
    
    /****** Object: Table [dbo].[Student] ******/
    
    SET ANSI_NULLS ON
    
    GO
    
    SET QUOTED_IDENTIFIER ON 
    GO 
    SET ANSI_PADDING OFF 
    GO
    CREATE TABLE [dbo].[Student]( 
    [StudentID] [int] IDENTITY(1,1) NOT NULL, 
    [Name] [varchar](50) NULL, 
    [Email] [varchar](500) NULL, 
    [Class] [varchar](50) NULL, 
    [EnrollYear] [varchar](50) NULL, 
    [City] [varchar](50) NULL, 
    [Country] [varchar](50) NULL, 
    CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED ( [StudentID] ASC )WITH (PAD_INDEX = OFF, _
    STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, _
    ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]  
    GO  
    SET ANSI_PADDING OFF 
    GO
  4. Right click on the solution, and add a new folder – ‘Entities’.
  5. Right click on Entities folder, select Add -> ADO.NET Entity Data Model.

  6. Give the name as ‘SchoolManagementDB’ and click OK.

  7. Select ‘EF Designer from database’ and click Next.

  8. Click on New Connection. Select the Server Name and Database Name on respective comboboxes.

  9. Click OK.

  10. Click Next and select the table – Student. Click Finish.

  11. This would create a file - SchoolManagementDB.edmx, in Entities folder. Rebuild the solution.
  12. Right click on Controllers folder, select Add -> New Scaffolded Item.

  13. Select ‘MVC 5 Controller with views, using Entity Framework’. Click on Add.

    • Select ‘Model Class’ and ‘Data Context Class’ on the ‘Add Controller’ screen. Click on Add.

    • This would add a ‘StudentsController’ and related views to Create/Delete/Details/Edit/Index for Student model.

  14. Now build and run the solution. Enter the URL in your web-browser – ‘http://localhost:XXXX/Students’, after replacing the XXXXX with the actual port numbers that you have received. This should open a screen like the following:

  15. Here, you can try creating new student information using the link – ‘Create New’. This would subsequently display the other links of Edit/Details/Delete on the same page.
  16. Now, we can link the Student views with the main application. Open the ‘_Layout.cshtml’ page, given under Views -> Shared folder. Search for the following link: 
    <li>@Html.ActionLink("API", "Index", "Help", new { area = "HelpPage" }, null)</li>
  17. Add the following line after the above link:
    <li>@Html.ActionLink("Student Info", "Index", "Students", new { area = "" }, null)</li>

    "Student Info" specifies Link title.

    "Index" specifies the Page name that should be displayed.

    "Students" specifies that Controller Name.

  18. Run the application, and now you can view ‘Student Info’ link at the top of your application:

  19. Here, you can click on the link – ‘Student Info’ and play around.

Authorization

  1. As a next step, we would put some authorization and validation in our application.
  2. Open the StudentsController class and add the attribute – [Authorize], above the class name:

  3. Rebuild the solution and run it. Now if you click on ‘Student Info’ link, it would ask you to first login and then let you go to the required page.

Validation

  1. As of now, if you try to create any new Student, it doesn’t ask you for any validation. Next, we would follow to provide certain validations like:
    • Name, Email, Enroll year should be mandatory
    • Email should be in proper email format.
  2. Right click on the solution and add a new folder, name it as “Resources”.
  3. Right click on new folder – “Resources” and click on “Add New Item”. Select file type – “Resources File”. Name it as “ErrorMessages.resx”. Click on Add button.

  4. Add some error messages in resource file, like the following:

  5. Add a new folder inside Entities folder, name it as MetaData. Add a new class file inside MetaData folder, name it as StudentMetaData.cs.

  6. Replace the contents of the above class with the following:
    C#
    using SchoolManagement.Resources;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    
    namespace SchoolManagement.Entities.MetaData
    {
     public class StudentMetaData
     {
    
     [Required]
     [StringLength(20, ErrorMessageResourceType=typeof(ErrorMessages), 
     	ErrorMessageResourceName="NameLength" )]
     public string Name { get; set; }
    
    
     [Required]
     [EmailAddress(ErrorMessageResourceType = typeof(ErrorMessages), 
     	ErrorMessageResourceName = "EmailFormat", ErrorMessage=null)]
     public string Email { get; set; }
    
     public string Class { get; set; }
    
     [Required]
     [Display(Name="Enroll Year")]
     public string EnrollYear { get; set; }
    
     public string City { get; set; }
    
     public string Country { get; set; }
     }
    }
  7. Add a new class inside Entities folder, name it as PartialClasses.cs. Add the following contents inside this new class:
    C#
    using SchoolManagement.Entities.MetaData;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    
    namespace SchoolManagement.Entities
    {
        [MetadataType(typeof(StudentMetaData))]
        public partial class Student
        { }
    }

    In the above three steps, we have defined a metadata class that would hold all our validations, and then linked this MetaData class to the main Entities class using the partial classes.

    We could have added all our validations inside main Entities class (Student.cs), but if needed to refresh Entities from DB, then it would remove all the validations.

  8. You can now build and run the application. While you try to add new Student without valid information, it would show the validation messages:

History

  • 21st April, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionno EF code first? ... no thank you Pin
Member 800306321-Apr-15 3:46
Member 800306321-Apr-15 3:46 
AnswerRe: no EF code first? ... no thank you Pin
RajKGoel21-Apr-15 17:41
professionalRajKGoel21-Apr-15 17:41 
QuestionThe image are broken link Pin
Cheung Tat Ming21-Apr-15 0:31
Cheung Tat Ming21-Apr-15 0:31 
AnswerRe: The image are broken link Pin
RajKGoel21-Apr-15 17:44
professionalRajKGoel21-Apr-15 17:44 
Questionhave you consider to post this as a tip? Pin
Nelek20-Apr-15 13:33
protectorNelek20-Apr-15 13:33 
QuestionError Using Resources file Pin
Member 1151667420-Apr-15 10:10
Member 1151667420-Apr-15 10:10 
Hello,
I got error "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type" at these 2 blocks of code

[StringLength(3, ErrorMessageResourceName = ErrorMessages.NameLength)]
public string Name { get; set; }

[Required]
[EmailAddress(ErrorMessageResourceName = ErrorMessages.EmailFormat, ErrorMessage = null)]
public string Email { get; set; }

Thanks
D.P
QuestionImages broken found in your article Pin
Tridip Bhattacharjee20-Apr-15 3:53
professionalTridip Bhattacharjee20-Apr-15 3:53 
AnswerRe: Images broken found in your article Pin
RajKGoel20-Apr-15 3:59
professionalRajKGoel20-Apr-15 3:59 
GeneralRe: Images broken found in your article Pin
Member 1004199021-Apr-15 22:01
Member 1004199021-Apr-15 22:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.