There are many types of validations that do allow in MVC Models such like Required Field Validator, Data Type Validator, Range Validator and etc… But there is a way that the developer can write his own Validation Rules and work with them as a normal validator that comes built-in. This is way far easier in MVC.

First Create a New MVC 3 Application. Create a new class in the Model or can use the existing one as well. Add a reference to System.ComponentModel.DataAnnotations.

using System.ComponentModel.DataAnnotations;

In this case, I am going to use as sample model named User for the validation.

public class User
    {
        public int UserID;
        public string Gender;
        public string Salution;
        public string UserName;
        public string FirstName;
        public string LastName;
        public DateTime RegistrationTime;
    }

I do need to validate the inputs{“Male” or “Female”} for Gender of the User and I would like to name that controller as GenderValidation.

Here comes the action.

Define a class named GenderValidationAttribute that inherits from ValidationAttribute. Then override the method IsValid from the Base class.

public class GenderValidationAttribute : ValidationAttribute
    {

          protected override ValidationResult  IsValid(object value,
 ValidationContext validationContext)
        {
            string gender = value.ToString();

            if (!(value.Equals("Male") | value.Equals("Female")))
            {
                return new ValidationResult("Invalid Input for Gender.");
            }
            return ValidationResult.Success;
        }

    }

Now this can be used as normal as a general Validation Attribute. Change the User Model like below.

public class User
    {
        public int UserID;
        [GenderValidation]
        public string Gender;
        public string Salution;
        public string UserName;
        public string FirstName;
        public string LastName;
        public DateTime RegistrationTime;
    }
, , ,

A meta data class is a class that defines something that could not be done in the class in the higher level. One of the key reasons that you would need meta classes is when you are using the Entity Framework. It is useless that you modify the validation controls in the Entity Model as it will be rebuilt when you build or debug the application. So the code that you added later to validate will not be there for any more.

In such cases, Meta classes will be useful. It’s just a matter of creating a new class and adding a sort of a reference to it in the entity class generated by the Entity Framework. This is quite simple.

For example, I am going to use a sample class named Customer in order to validate it from outside.

public class CustomerMeta
{
    [Required()]
    public string Name;
    //More code goes here
}

Now add the MetadataType attribute to the class located in Entity Framework. This will not be removed per each rebuild of the application.

[MetadataType(typeof (CustomerMetaData))]
public partial class Customer
{
    public string Name;
   //Variable and method declarations
}

At last, you will have to gets two using statements for both the classes. I will let you know what they are.

, , ,

JavaScript Object Notation (JSON) is highly used in today’s communication. The main reason is that it does not depend on the programming languages that you use for programming. In simple terms, a JSON object that is returned by a .NET application can be easily read by a Java Application. The only requirement is a particular URL that returns a single or many JSON objects.

A common example is Twitter’s Public Timeline. http://twitter.com/statuses/public_timeline.json

As usual you can create new ASP.NET MVC 3 Application or can use an existing one. In ASP.NET MVC, we do usually return a JSON object through a controller. For an example, I do create a user class which is a model.

class User
{
    public int UserID{ get; set; }
    public string UserName{ get; set; }
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
    public DateTime RegistrationTime{ get; set; }
}

Then I create a method that returns a JsonResult in the HomeController. The JsonResult that it returns is an instance of a User.

public JsonResult UserInfo()
{
    User user=new User();
    user.UserID = 1;
    user.UserName = "Rockmarley";
    user.FirstName = "Malin";
    user.LastName = "De Silva";
    user.RegistrationTime = DateTime.Now;
    return this.Json(user,JsonRequestBehavior.AllowGet);
}

Then browse the URL http://localhost:52446/Home/UserInfo {Change the port as it is configured on yours}
Here you do not need to have a View for the method specified in the controller. Since it does not return an ActionResult, the View will not be taken into the count even if it was there.

, ,

ASP.NET provides you a greater set of capabilities for working with a proper authentication. This is made available with the Membership Provider in it. Membership provider provides rich set of features including adding new users and assigning them specific roles.

By default, once you create an ASP.NET Application (Not empty application), it provides the capability of registering the users and sign-in them. But, how does this work, where are these registration data are stored? As soon as you create an application, just check the folder structure by browsing it through Windows Explorer. (In Visual Studio: Right-click on Application->Open Folder in Windows Explorer) Go inside the App_Data folder and you will find nothing inside in it.

Go back to Visual Studio and Run the application. Then create a new user account (Register). Once you are done, re-check the App_Data folder. You will find a database and a log file created named ASPNETDB. This is the file created for storing the user information by default. You can see a new connection string is made in Web.config file.

So, the Database name remains as ASPNETDB. But we do need to have a different name which has a relevance to our application. Basically, this database includes a set of tables and views. We can add them into our own database or a new database with a name which we would like to have. ASP.NET SQL Server Setup Wizard provides this opportunity. This tool is located in “[drive:]\%windir%\Microsoft.NET\Framework\version” folder of the file system. Once you get in there, open the aspnet_regsql application.

You can either Configure SQL Server for application services or Remove application services from an existing database. Once you get it done, you will have the required tables and fields in the database you want.

Assigning Roles to Users

A user can have many roles. A role defines something that a particular user needs to have. For example as user may need to have access to Health Department and the Transport Department. In such a scenario, what we can do is create two Roles for Health and Transport Departments and assign the user to both. When we are rendering the views or executing the methods, we can restrict by User Role. But, how are we gonna have this Role feature?

Visual Studio provides a tool named ASP.NET Configuration for this. You can find it in the Solution Explorer. It is a tool with a web interface. It will be browsed with the parameter applicationPhysicalPath in your web browser. Just go to the Security tab and click on the link Enable Roles. There you can view the Existing Users as well as you can create User accounts from there.

Once you Enable the Roles, you can create the roles and assign users to the system through this tool. Also you can have all those features in your web application it self. Lets discuss them in another article.

The web.config file will get changed once you change the Enable Roles feature and all the roles you create will be stored in the database.

<roleManager enabled="true">
      <providers>
        <clear />
        <add connectionStringName="ApplicationServices" applicationName="/"
          name="AspNetSqlRoleProvider"
          type="System.Web.Security.SqlRoleProvider" />
        <add applicationName="/" name="AspNetWindowsTokenRoleProvider"
          type="System.Web.Security.WindowsTokenRoleProvider" />
      </providers>
    </roleManager>

In MVC, the controllers can have the attribute [Authorize(Roles="Health")] like such and restrict the users by accessing them.

, ,

Basically, a controller defines what are the view that should be rendered to which user and how it should be done. A controller can have a set of return types.Basically a controller looks like this.

public ActionResult Index()
{
    // Add action logic here
    return View();
}

A controller action returns an action result in response to a browser request. A controller can have methods, that do not return Action results as well. There are many types of action results that can be returned.

  • ViewResult – Represents HTML and markup.
  • EmptyResult – Represents no result.
  • RedirectResult – Represents a redirection to a new URL.
  • JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
  • JavaScriptResult – Represents a JavaScript script.
  • ContentResult – Represents a text result.
  • FileContentResult – Represents a downloadable file (with the binary content).
  • FilePathResult – Represents a downloadable file (with a path).
  • FileStreamResult – Represents a downloadable file (with a file stream).

There are particular scenarios that Controller can control.

1) Enable rendering view to Authorized users only

This can be simply done using adding [Authorize] tag before the Controller methods.

  • [Authorize(Roles="Admin")] – You can create a particular user group by going to ASP.NET configuration. A set of users can be grouped and assign a role. For example, the Admin panel views can be restricted using this. This is used when there are a lot of users that do need access to particular view.
  • [Authorize(Users="malin,user1")] – Rather than having user groups and assign roles, if you just have a single or two to three users, you can simply add Users attribute.
  • [Authorize] – Some features such like Profile Page are viewed to every user who do have logged into the system. The requirement is just to make sure that the users have logged into the system.

2) Execute controllers when there are form value submissions

A view can submit forms via HTTP or HTTPS protocols using GET, POST or PUT method. There are controls that needed to be put in the previous line of the controller method to make it happen.

[HttpGet]
[HttpPost]
[HttpPut]

For example, the following method will be executed in a case of form submission via POST method.

[HttpPost]
public ViewResult Details(int id)
{
user user = db.users.Single(u =&gt; u.userID == id);
return View(user);
}

In the example above, I do pass an Entity Model as well along with the View.

3) Pass data through ViewBag

Sometimes, you may need to pass some values to the particular value from the controller. ViewBag is a simple method of making it happen.

ViewBag.FirstName = "Malin";
ViewBag["LastName"] = "De Silva";

This values can be accessed in the view simply as the way it is sent.

@ViewBag.FirstName

There are many more features that are facilitated with Controllers. Here are just simply the basics of them. I will make them available in next posts.

, ,

Generally, the coding that we type in the .cshtml or .vbhtml file in a MVC 3 view is rendered through a view engine. Before MVC 3 come into action, ASPX was the View engine used to render the content. MVC 3 introduces a new view engine named Razor. Razor is an effective rendering engine that is introduced with ASP.NET MVC 3. It has simplified syntax along with the easy and cool capabilities provided for the developer to use with. It is easy to use and will not get complicated with the syntax that was available in ASPX View engine.

A much descriptive article on Razor syntax is available at the MSDN.

If you create a View in ASP.NET MVC, it will allow you to create one of the CRUD operations that you would like to have. How are we going to add another operation of the same entity or another in the same View. There are 2 ways that it can be done. We can add a User Control or a Partial View. Both looks like same for a particular extent. User controls have an implementation of events whereas partial views do not.

Creating a Partial View is not that big thing. You just need to try adding a View by right-clicking on the sub folder under the Views folder. Then the Add View window will open. It is advised that the partial views must start with “_” prefix. It makes it easy to identify that as a partial view. Then click the checkbox in front of the Create as a partial view. Since I do have created a model class in my project, I can select it as the model. The way how Model can be modeled is described in a previous article.

Then the partial view will be created. Now it’s time to add it into a View. Just go to the view that you would like to add the partial view and type,

@Html.Partial("_Index")

Then the content in the created partial view will appear in the View where it is defined to be located. There are some minor issues when having two forms in both partial view and the View. For example adding the User and adding a Product in the same. Lets discuss more about Partial views and the ways how it can be done in an upcoming article.

, , ,

It’s easy. How long will you need to create a full functional MVC Application? You will be able to create a fully functional ASP.NET MVC 3 application within less than 5 minutes. It will take a few mouse clicks and you will get an application that is possible of performing all CRUD(Create-Read-Update-Delete) operations.

Step 1: Create an Empty ASP.NET MVC 3 Application and Attach Database

As we did in previous examples, you can create an empty application using Visual Studio 2010.Then go to the main menu of Visual Studio 2010. Under the Project tab, select Add ASP.NET Folder and select App_Data. App_Data is the folder that is going to keep the database of the application that we create. If you are going to work with a database that is created in SQL Server, then you do not  need to create this folder. The database can be connected once we are creating the Model.

Step 2: Creating the Model with Entity Framework

Right click on the Models folder of the Solution Explorer and then proceed Add–>New Item. Then select Data from the installed templates that are available in the popup window. Choose ADO.NET Entity Data Model and change the name to MyModel. Then click Add. The Entity Data Model Wizard will open. Select Generate from Database and proceed Next.

Since my database is available in the App_Data folder, it automatically takes my Database and create the connection string. When you click Next, the and entity connection named dbEntities will be created in the web.config file.

Then choose the Database objects. You can select the tables and views as your need. For this application, I select the available table in my database. Then click Finish.

A visual representation of the model will be created as a new file named MyModel.edmx.

Step 3: Creating the Controllers and the Views

First you will have to build the application for once. (Shift+F6) Then right click on the Controllers folder of the Solution explorer and proceed to Add–>Controller. Since I am planning to create the CRUD operations for the User table, I do give the controller name as UserController. Remember the convention, every controller must have the suffix “Controller” in its name. Then select the 2nd option of the Templates drop down list. If you did not build the application after creating the model, There will be an error saying no Model class is found. Then try building the application. In this case, I do select User class as the Model class and dbEntities class as the Data Context class. I keep the view engine as Razor and click the Add button.

Now we are done. This won’t take even 2-3 minutes when you are doing it next time.

Then you will see a sub-folder created named ‘User’ under the Views folder. This is because the controller name we gave was User. Under that folder, you will see 5 .cshtml files for CRUD operations and listing.

Run the application:

  • To view user list: http://localhost:port/User
  • To create a new User: http://localhost:port/User/Create
  • To Edit an Existing User: http://localhost:port/User/Edit/Id
  • To Delete an Existing User: http://localhost:port/User/Delete/Id
  • To View an Existing User in detail: http://localhost:port/User/Details/Id

The source code of the application available here:  Entity Framework Sample

, , ,

I created a sample Model for the student in Creating a basic ASP.NET MVC Application-Part I. There I have created a simple Model where it defines the data types that each variable or the field can have. Simply, the only restriction of the DateOfBirth variable is that it need to in type of DateTime. But there are many more things to validate in that field. For example, a user can give upcoming date as the Date of Birth. How these things can be validated? Models in ASP.NET MVC 3 provides the greater capabilities for that. Let’s discuss them in detail here.

First of all, add the following using statements in the model.

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

1) Customizing Display Name

By default, the View displays the name of the Field as the Field name in a form table or whatever the display mode. For example the First Name of the student will be displayed as FirstName (no space in between)since we have not declared what should be displayed. We do need to display it as First Name. What we have to do is simply adding the [Display].

[Display(Name="First Name")]
public string FirstName { get; set; }

2) Required Field Validation

As it says, this is for validating the required fields. Basically a form or an entity may contain things that are must to have. For example, a person who create an account for a log-in must have a Username and Password. In our student example, the student must have almost all the fields. Will we find student without a Date of Birth, Address? No. So all fields are required fields.

Required field validation can be easily done by adding [Required] before the variable declaration.

[Required(ErrorMessage="First Name cannot be empty.")]
[Display(Name="First Name")]
public string FirstName{ get; set; }

Here I have added a custom error message as well. So in a case that First Name is unavailable, this error message will prompt. if the ErrorMessage was not there(when we have only [Required]), then the default error message of MVC will be displayed.

3) Data Type Validation

It provides the capability of making formatted content to be made available. For example, a password must be represented in special characters. It can be simply done by setting the Data Type for Password. Then it will create a PasswordFor control over TextBoxFor for editing when you generating the view.

[DataType(DataType.Password)]
public string Password { get; set; }

Likewise, you can have data types such as Date,DateTime, Currency,Email Address and etc…

4) Filed Length Validation

There may be a particular length range that you might need to have in a filed. For example, you may need the password to be minimum 6 characters in length and maximum of 20 characters. It can be simply defined like this.

[MinLength(6,ErrorMessage="Password must contain more than 5 characters.")]
[MaxLength(20, ErrorMessage = "Password must be less than 20 characters.")]
public string Password { get; set; }

5) Comparison Validation

When creating an account, you may ask the user to Retype the password. In such case, it must be same as the first Password. It can be simply done through [Compare].

[Display(Name = "Password")]
public string PWord { get; set; }

[Display(Name = "Confirm Password")]
[Compare("PWord",ErrorMessage="Passwords do not match")]
public string CPWord { get; set; }

Here are the most commonly used validations that I have seen. There are many more that would be nice to tryout such as [Association],[AllowHtml],[Range] and etc…

Just try them out. Feel free to leave a comment if any questions are there.

, , , ,

In the previous article, Creating a basic ASP.NET MVC Application-Part I we discussed about creating a User Interface to a Model defined as Student. Then we build and run the application. Going back to the application, The Controller named StudentController calls the Index method so, the Index.cshtml of the Student sub-folder in the Views folder will be deployed. In the Index.cshtml view, we do have referred the Student Model in the Models folder.

Read the rest of this entry

, ,

As I said in the previous article Getting Started with ASP.NET MVC 3, Models implements the logic of data domain of an application. It defines the way how the data should interact with the users of the system. In another way, ASP.NET models assure that the data are in the appropriate format before it gets inserted or retrieved from a database. It does not mean that the Databases are the only interacting component of the model. Users can simply create data objects as well. The beauty of MVC 3 is that it facilitates the Model to be modeled with Entity Framework. So it can be done within a few clicks.

Read the rest of this entry

, , ,