Registration Form With ASP.NET MVC

Today, we’ll make a registration form on the basis of what we have already learned previously.

  • Razor Engine
  • And MVC (Model, View, Controller)
  • Data Annotations

And we’ll explore:

  • Scaffolding
  • Introduction to Context class
  • Connection String
  • Debugging

Note
Today, we need 2 tools:

  • Visual Studio 2017
  • SQL Server

But if you haven't installed SQL Server, then don’t worry; when you install the Visual Studio 2017, you might check ‘.Net desktop development’.

ASP.NET

 

If you check it or if you check the SQL Server localdb checkbox from the Summary then it is ok. You can continue with the tutorial. But if you haven't installed localdb or you’ve not SQL Server then you should install SQL Server and continue with the tutorial.

Let’s start our journey.

  • First of All Open Visual Studio and Create New Project ‘RegistrationApp’
  • Select Empty Template and MVC Reference.

    ASP.NET

  • Add Model class Name ‘Student’

And copy the previous blog final code and paste it into your model class under the namespace. And now your model ‘Student.cs’ file looks like this.

  1. using System;  
  2. using System.ComponentModel;  
  3. using System.ComponentModel.DataAnnotations;  
  4.    
  5. namespace RegistrationApp.Models  
  6. {  
  7.     public class Student  
  8.     {  
  9.         [Required(ErrorMessage = "Please Enter Name e.g. John Doe")]  
  10.         [StringLength(30, MinimumLength = 3)]  
  11.         public string Name { get; set; }  
  12.    
  13.         [Required]  
  14.         [EmailAddress]  
  15.         public string Email { get; set; }  
  16.    
  17.         [Required]  
  18.         [Compare("Email")]  
  19.         public string RetypeEmail { get; set; }  
  20.    
  21.         [DisplayName("Phone Number")]  
  22.         public string Phone { get; set; }  
  23.    
  24.         [RegularExpression("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")]  
  25.         [Required]  
  26.         public string Cnic { get; set; }  
  27.    
  28.         [Range(18, 25)]  
  29.         public string Age { get; set; }  
  30.    
  31.         [StringLength(35)]  
  32.         public string City { get; set; }  
  33.    
  34.         public string Address { get; set; }  
  35.    
  36.         [Required]  
  37.         [DataType(DataType.Date)]  
  38.         public DateTime? DateOfBirth { get; set; }  
  39.     }  
  40. }  

Scaffolding

Scaffolding is all about automation. We generate the automated code, files, folders through scaffolding in our project. It helps us to generate the readymade CRUD operations code. Microsoft continuously works to make the code easier for the developers.

But honestly speaking, if you’re new to programming in MVC then you should avoid it. You should know the basic things like what it is, how we use it and when we use it.  But if you want to be a good programmer then you should write the code yourself. Because if you use scaffolding and generate the CRUD operations code in the beginning and don’t understand the code then you’ll experience the worst moments in your professional life. But if you need to show some quick demos to any person then you can use scaffolding.

You can also make your own customized scaffolding template using T4 templates according to your requirement.

So let’s perform scaffolding and generate our ‘Student’ class Create Read Update Delete (CRUD) methods as well.

  • Right Click on ‘Controller’ Folder and Add Controller.
  • You’ll see this window.

    ASP.NET

Look at the above image window which has the title ‘Add Scaffold’, this window is all about scaffolding in MVC Controllers, Web APIs.

And now you need to select the third option. It is using Entity Framework and it will generate the Controller Actions as well as their views.

It means your complete operation will be completed just in a few moments.

But if you select the second option here then it will generate just CRUD actions, not views. We need to generate their views manually.

What is Entity Framework?

Before .NET Framework 3.5, developers used the ADO.Net Framework to fetch the data from the database, to insert the data into the database, create the database connection, make the DataSet containers and then convert the data into the database. It was really a huge headache for the developers to write such huge code. Microsoft introduced Entity Framework to make the code less cumbersome . Now we have predefined functions which insert our data, read our data and everything you want to play with data.

We’ll discuss Entity Framework in detail later on.

Let’s come back to the point.

ASP.NET

Model class

We’ll select our project model class because Entity Framework will write the operations on the basis of this class. So make sure it is ‘Student’ here.

We can say this class is Model class or Entity class because the table will be generated in the database on the basis of this class. Data context class: Context class is actually a bridge which connects our model class and database. So here we don't have any context class. Click on + sign after the context class textbox and add default context class. We’ll explore it in detail later.

And now, your window looks like this.

ASP.NET

Now you might be bothering about ‘async controller actions’ checkbox.

We’ll explore it later, it’s a complete topic.

What is the purpose of Reference Libraries?

We already know that validations are of two types.

  • Client Side
  • Server Side

In the previous article, we’ve applied the data annotations on model class properties which means that it is server side language so we make server side validations. But now we want to create the client side validations as well. Microsoft has written some JavaScript libraries which make the client side validations, and in the same way, we create our server-side validation just by checking ‘Reference Libraries’ checkbox. It reduces lots of code and effort.

It actually adds 2 main libraries in this scaffolding,

  • jquery.validate.min.js
  • jquery.validate.unobtrusive.min.js

You would only need these libraries on the form to validate what the user has entered into the form. Read

And finally, now press ‘Add’ button. And you’ll see:

ASP.NET

 

Oops! I’ve got an error.

ASP.NET

 

Don’t be scared, if you want to become a successful programmer then you should play with errors as much as you can.

This error is telling us whenever you create/update the model class, you should build your project before doing anything.

Ctrl + Shift + B = Build the Project

Actually, it is an error to get the type ‘Student’ class and if we build the project, our class assembly will be created, otherwise  we just write the code in Visual Studio IDE and expect that it should work. Then, this expectation is wrong until you build the project and then expect something on the screen.

Now come back and try once again after building the project successfully.

Add the controller into the project like we did before here. And once again, I got an error

ASP.NET

 

This error is telling us that the class ‘Student’ which you’re using to generate controller CRUD actions with views has no primary key. We already know that Entity Framework generates the database based on our model class and our class has no primary key. And we know that each table must have the primary key, then what are we doing actually?

Let’s add another property named ‘Id’ in our model class.

  1. public int Id { get; set; }  

 

And now rebuild the project. And try again once more to add the controller. And finally, it is done. We’ve successfully created our actions with views through scaffolding.

Look at all the files and code in these files that scaffolding has created for us. In short, it has made our lives  a lot easier.

ASP.NET

 

Scaffolding has created the CRUD actions into our ‘StudentsController’, we’ll explore them line by line later. But now just watch the action names and how we request it in the browser and now revise the pattern to request the controller actions in your mind.

ConnectionString

Now let’s come to Web.config file, here you’ll see the connection string in these tags.

  1. <connectionStrings></connectionStrings>  

 

All this happens with Scaffolding. Our Connection String looks like this:

  1. <connectionStrings>  
  2.   <add name="RegistrationAppContext" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=RegistrationAppContext-20180228230139; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|RegistrationAppContext-20180228230139.mdf"  
  3.     providerName="System.Data.SqlClient" />  
  4. </connectionStrings>  

What is the Purpose of Connection String?

Connection String is a string which has information about the data source -- either database name, server username and password and the driver information which helps to access this file. In short, it is used to connect the database with our application.

We have localdb information in this connection string. Actually, localdb is the database specific to the project. If you use this connection string then you’ll create the database inside the application. But it is not a good practice to use localdb, you should make your database into a SQL Server, because we can reuse the database of SQL Server but localdb is just project specific so we can’t reuse it.

Still, at this moment, the database isn’t created for your project. When we run (Ctrl + F5) and request the controller’s action where we’ve applied some operations relevant to the database then Visual Studio takes some time on that request and creates the database in localdb and when we show the files we can see localdb created a database. And we can include it in our project.

Now if we open the Tables folder in server explorer, our ‘Student’ table has been created.

ASP.NET

 

But according to the Software Engineering, it is not a good approach that we are creating the database on running the application. Our database should be ready before our development. Keep in mind, without a database never do programming of your application. First, create the database and then do development.

Now, let’s test our validations which we’ve created. Now, open the Create Url and submit the button.

ASP.NET

 

How to write Connection String in an easy way?

Now let’s see how to write the connection string in an easy way. You might have no localdb installed in your system but you have SQL Server so let’s make the database into our SQL Server.

Look when we open SQL Server Management Studio, SSMS asks for some credentials from us. Let’s review them.

These are the credentials, as we are working on our computer so we need just windows based authentication. But if we want to deploy our database on the server, then we need to select SQL Server based authentication and provide its username and password as well.

Look at the above the image and write the connection string,

  • Copy your server name from SSMS and paste it into connection string and semicolon.
    1. Server=Servername + semi colon (;)  
    2. OR  
    3. Data Source= Servername + semi colon (;)  
    4. <add name="RegistrationAppContext" connectionString="Server=DESKTOP-2FA7R8U;" providerName="System.Data.SqlClient" />  
  • Now we need the Database name. In our case, we don't have a database but we need to make our database. It will be automatically generated because it doesn’t exist.
    1. Database=Databasename + semi colon (;)  
    2. //OR  
    3. Initial Catalog= Databasename + semi colon (;)  
    4. <add name="RegistrationAppContext" connectionString="Server= DESKTOP-2FA7R8U;Database=RegistrationApp;" />  

The best practice to name the database is it should be same as the name of our project. Because it reminds you that this database is important and it is of that project.

Now Authentication Type. If we want Windows based authentication then

  1. Trusted_Connection=True;  
  2. //OR  
  3. Integrated Security=True;  
  4. <add name="RegistrationAppContext" connectionString="Server= DESKTOP-2FA7R8U;Database=RegistrationApp;Trusted_Connection=True;" /> 

 

But keep in mind, if you’re using Server then you’ll use Trusted_Connection and if you’re using Data Source then you’ll use Integrated Security. You should know about these patterns from connectionstrings.com

Now we need to tell about which type of server because it can be any server -- it might be wamp, xamp, sql server. So,

  1. <add name="RegistrationAppContext" connectionString="Server= DESKTOP-2FA7R8U;Database=RegistrationApp;Trusted_Connection=True;"providerName="System.Data.SqlClient" />  

And we’re working on SSMS which is actually the desktop client of SQL Server. SQL Server services are running under the hood. We just work on SSMS, so its name is SqlClient.

  1. providerName="System.Data.SqlClient"  

This statement is actually the driver through which we can easily access the database from our code and manipulate any database related operation.

Now the final look of our connection string is,

  1. <add name="RegistrationAppContext" connectionString="Server= DESKTOP-2FA7R8U;Database=RegistrationApp;Trusted_Connection=True;"providerName="System.Data.SqlClient" /> 

 

Let’s run the application now. And it is successfully run. Let’s see the database in our SSMS (Sql Server Management Studio)

ASP.NET

Validations

Let me first explain the types of validations.

Client Side Validation

Client Side Validations occur in the browser. They appear with instant response into the browser. They are user-friendly instead than server side validation. It appears in the browser before submitting the form. The messages which guide you on how to input the data, what kind of data should be, what kind of pattern should be  are provided by client side validation.

  • HTML5
  • Javascript code
  • JQuery

These programming languages are important for client side validations. HTML5 has the built-in feature of HTML5 Validations. Its performance is much better but it can’t be customized.

Server Side Validation

The validation which appears on form submission is called Server side validation. But in client side, the messages appears without the request going to the server. Here server side code is responsible for the server side validations.

ASP.NET

 

Our CNIC pattern validation message is not good. Don’t worry and just add ErrorMessage and rerun the application.

  • When we click on the Create Button Server side validation occurs and browser link refreshes.
  • But when we’re filling in the form, we see the different messages on filling in the fields. These are client validations.
  • These client validations are enabled due to the check of the ‘Reference Libraries script’ as we’ve discussed above. This client side validation is enabled due to those libraries and our validation is working on the Create page.

    ASP.NET

Let’s open ‘Create.cshtml’ and see how it works.

Yes these are the libraries which are placed at the bottom of ‘Create.cshtml’ file and enable client side validation.

You might be thinking about these if these libraries are so useful, we should place them at _layout.cshtml then it will support all the pages. But how can you make sure that every page in the application has form, and if there are pages in which there is no form the extra http request load increases on the server. Because when we open the page on the browser then it will load with its credentials. And if we don’t have any need of these files then it will request these files again and again to the server. That is not good.

How does this Server Side Validation Works?

We know that request goes to ‘StudentsController’ and ‘Create’ action. And server side validation works when we submit the form on POST Request. So this is the check which enables server side validation.

ASP.NET

 

We already know that the Web is stateless and Http is a stateless protocol and you might have heard from somewhere that models are used to maintain the state of the application. You can see in the above figure, if the modelstate is valid then it is ok. But if the model state is not valid then our model is full which has some validation errors will return back to the view and show the data with validation message in view. This is how we maintain the state of the application with model classes.

Debugging

Finally, let’s learn the last thing of today’s tutorial.

  • Make breakpoint at this check (F9 on this line)
  • Press F5 (Build with Debugging)
  • And Fill the form and click on ‘Create’ Button
  • Now let’s explore how to check the worst case if there is any error.

    ASP.NET

You can analyze each key value manually if the Error  Count = 0 it means it is ok. But if count is greater than 0 then in this field you’ll find a problem.

See Also


Similar Articles