Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / C#

ASP .NET MVC for Beginners in Web Development

Rate me:
Please Sign up or sign in to vote.
4.85/5 (67 votes)
29 Apr 2014CPOL24 min read 323.8K   114   15
Introduction to ASP .NET MVC 5 for .NET developers that are completely new to Web development, MVC frameworks and Web Application Frameworks in general.

Introduction

This tutorial is aimed at .NET developers that are total beginners in the Web Applications world and want to get started using familiar Microsoft .NET technologies.

Prerequisites

  • HTML – basic skills (structure of a web page, tags)
  • CSS – basic skills, including basic familiarity with the Bootstrap framework
  • C# - you should be fully comfortable writing C# applications, and be familiar with the following features:
    • LINQ
    • Anonymous Types
    • Expressions
  • .NET Framework libraries – you should be familiar with popular framework features, such as:
    • Entity Framework Code First (basic)
    • Dynamic variables

Development Environment

In this tutorial I will be using Visual Studio 2013 Ultimate edition for all demonstrations. You may use any edition of Visual Studio 2012 and upwards. There is a free Express version available – be sure to download the Visual Studio Express for Web edition.

If you are not using Visual Studio 2013, you will only be able to create MVC 4 items unless you install the ASP.NET and Web Tools 2013.1 for Visual Studio 2012 package, whereas the examples will be based on ASP .NET MVC 5. That’s okay though, as the differences between the versions are mainly in authentication features and not in syntax.

What are Web Application Frameworks?

Put simply, Web Application Frameworks allow you to create applications which generate HTML pages (typically, though there are other types of responses which we will brush on later) dynamically, rather than storing pre-created HTML pages on your web server.

This allows the creation of powerful, smart websites that do way beyond displaying static data. Most dynamic websites (meaning websites that do not only display static HTML pages) in the world today are created using some sort of a Web Application Framework.

What is MVC?

MVC is not a Microsoft technology. It stands for Model View Controller. It is a common design pattern that exists in many Web Application frameworks such as Ruby on Rails, Django and Zend Framework. MVC is commonly used to structure user-oriented applications (meaning applications that have a Graphical User Interface – GUI).

MVC is somewhat similar to MVVM (Model View View-Model) if you come from the WPF world, but we will not be delving into the differences between these in this tutorial.

Model

A model is a plain vanilla class that represents the structure of your data that you want to make visible to the user. A typical Model class would only include ‘dumb’, public properties. For example, for the Person model you would include the following properties:

  • Name
  • Address
  • Email
  • Phone

Other components of MVC will use the Model classes to perform logic (for example, add a Person to a database) and to display it to a user (render an HTML page displaying data about John Smith).

It’s important to realize that this Model is intended for the View, and not necessarily for the entire application. It is perfectly normal to have a Person Model class that is used internally in your application, in the server side (for example, processing credit card details for a Person), and then have a Person Model class in the MVC project. This is called a View Model.

View

A View is the result that the user will see when interacting with our Web Application. This is typically an HTML page, but it can also be raw data represented by XML or JSON, or binary data (for example, a .zip file).

Views are created dynamically by the Web Application Framework when the request is performed by the user, and are not stored on the server (beyond caching mechanisms that are implemented internally).

Controller

A Controller is a class which performs the linkage between the View and the Model. For example, if a user requests a list of all the Persons in our application, the controller class will contain the code which accesses the database, queries it for the appropriate user set, and then creates a View with the given Model (which would be a list of the Persons returned from the database).

Each controller exposes a set of public methods, called Actions. This is your application’s API. Each View is associated with a single controller, but a controller may have multiple Actions that return different Views.

Putting your business logic into the Controller class is bad practice. The Controller should only be responsible for retrieving data & processing it, while the business logic itself should be delegated to the appropriate classes and interfaces that may not even necessarily be a part of the MVC Web Application.

Routing

Routing is the process responsible for resolving, or routing a URL into a specific Action in a specific Controller. For example, if our imaginary Person application is hosted at http://www.mypersonmanager.com, and we want to call the GetPersons Action, which is a method in the Person controller class, our route will typically look something like http://www.mypersonmanager.com/person/getpersons.

Routing is also used to pass parameters for Actions. For example, if we have a GetSpecificPerson Action which accepts an Id parameter and we want to call it with the Id being 6, we will typically pass a parameter to it in the following syntax: http://www.mypersonmanager.com/person/getspecificperson/6.

Note that the syntax presented here is a generic example, and while most Web Application Frameworks generally follow these conventions, there might be differences between them.

What is Microsoft ASP .NET MVC?

Simply put, ASP .NET today can be referred to as the set of technologies and libraries that underlies the ASP .NET MVC Framework.

ASP .NET Web Forms

ASP .NET Web Forms is what .NET developers used to call “ASP .NET”, prior to the introduction of ASP .NET MVC (hence the confusion). It introduced concepts that are similar to developing Windows Forms applications – including draggable controls, page state and code-behind files.

The main advantage of ASP .NET Web Forms is the ease of creating a Web Application, which can initially be created with little to no code at all, using controls from the Toolkit. However, Web Forms doesn’t enforce modern design patterns, may sometimes create cluttered and non-standard HTML pages and couples the user to Microsoft controls & JavaScript libraries.

ASP .NET Web Forms still lives and is used by many .NET developers.

ASP .NET MVC

ASP .NET MVC was introduced in 2008 and is based on the ASP .NET stack, as a competitor to existing, prominent open source MVC Web Application Frameworks such as Ruby on Rails and Django. Like them, ASP .NET MVC is open sourced.

The main advantage of ASP .NET MVC is that it is more flexible, and allows you to use external libraries, implement your own logic, and creates clean, compatible HTML pages and application logic that is easily testable. It does, however, require a steeper learning curve and generally speaking, more code.

Your First ASP .NET Application - PersonManager

Creating a new ASP .NET MVC application

Our first application will be very simple: it will load a set of users from a database using Entity Framework, and display them to the user. It will also allow adding a new user to the database.

To create a new ASP .NET MVC Application, you will need to create a new project, and go to the Web tab. If you are using Visual Studio Express for Web, you will immediately see this project option when creating a new project.

Image 1

In this case, choose the MVC option, then click the Change Authentication button and choose No Authentication. In earlier editions of Visual Studio, this screen may look a bit different. Be sure to uncheck any additional options if they exist in your edition. We will not be exploring other templates in this tutorial, but you may try them out if you want – they include pre-created demo apps that can be useful for learning.

Visual Studio will create a default application with pre-created Models, View and Controllers.

Convention over Configuration

ASP .NET MVC follows the popular Convention over Configuration principle, which favors naming conventions over complex configuration files that define what’s what.

To get started with ASP .NET MVC, familiarize yourself with the following conventions:

  • Controllers must be named in the syntax NameController and are placed in the Controllers folder.
  • Views don’t have a specific naming convention, but must be placed in the Views folder.
  • Application Data, such as additional configuration files, binary files or local database files, should be placed in the App_Data folder.

Creating a Model

The Model is the backbone of our application, and therefore we will create it first. In this case, we’re only have one Model – person. Let’s create that class in the Models folder.

C#
public class Person

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Address { get; set; }

    public string Email { get; set; }

    public long PhoneNumber { get; set; }

}

As promised, this is a very simple class that has nothing special to it, only plain properties.

Creating a Controller

For now, leave the existing Controllers and Views created by Visual Studio intact. Create a new Controller by right clicking the Controllers folder and then Add -> Controller. In the scaffolding dialog which shows, choose MVC 5 Controller.

Image 2

Again, if you have an older version of Visual Studio (MVC 5 is supported from Visual Studio 2013 and upwards), you may see a different dialog. Be sure to create an empty MVC controller either way.

Image 3

Name your controller PersonController. Remember the controller naming convention!

As you can see, this brand new controller is a simple class which inherits from Controller, and contains only one method – Index, which returns the View associated with this Action.

C#
public ActionResult Index()

{

    ViewBag.MyHeader = "Hello World!";

    return View();

}

Creating a View

Each Action can be associated with a View, without having to explicitly name the View (as you could see, the Index method calls the View method without any parameters). This association is created by another instance of convention over configuration. If your Action is called Index, ASP .NET MVC will automatically look for a View called Index (you can name it differently, and use an overload of the View method which accepts a View name). Go ahead and create a new View by right-clicking within the Index Action, then clicking Add View.

Image 4

As you can see, Visual Studio already knows how to name this Controller, because you’ve clicked inside the Index action. Now go ahead and create the View.

Let’s take a look at the result.

ASP.NET
@{

    ViewBag.Title = "Index";

}


<h2>Index</h2>

ASP .NET MVC Razor Markup Syntax

As you can see, this page has HTML tags, but it also has a special syntax, the ‘@’ character, which indicates a block of C# code, and not HTML, is ahead. This is called markup syntax – the core of the magic of ASP .NET (or any Web Application Framework, for that matter). This is what allows you to create dynamic content and not just write static HTML pages.

ASP .NET MVC supports different view engines, which are responsible for rendering the View’s HTML. The default view engine is called Razor and was designed for ASP .NET MVC, and for our purposes, there are no reasons for using a different one. Different view engines may have different markup syntaxes (for example, the classic ASP .NET engine uses <% tags).

Razor has a pretty smart markup syntax, that doesn’t need terminating tags like some other engines do. For example, you may do the following:

ASP.NET
<ul>

    @for (int i = 0; i < 10; i++)

    {

        <li>@i</li>

    }

</ul>

As you could intuitively tell, the result of this simple markup block will be a list containing the numbers 0 to 9.

Razor knows that a C# for statement is beginning thanks to the @ character. It then searches for brackets that indicate a block of code is ahead. Had we not included this character, Razor would treat this as regular text.

Also note how Razor knows to interpret a block of code in the middle of HTML syntax – we use the @i statement to indicate that we want to place the current value of i inside the list item, and we don’t need to make a line break or close the tag in either way. This is only valid if we’re just printing a member. You can’t place a for statement in the same manner, for example.

Code in markup sequences is your familiar C# and .NET, and you may use whatever namespaces you like by adding a @using statement at the top of the page – again, just like a regular class. You may also place breakpoints on Razor markup segments, which will be triggered at runtime.

If you find yourself writing a lot of code in the View, double check yourself. The View should only contain code that renders the data from the Controller for textual representation. Code that interacts with the data, performs calls to external resources or can be (even hypothetically) reused outside the View, should always go in the Controller.

ViewBag

ViewBag is simply an object that’s shared between the Controller and View. It’s a useful way of transforming blocks of data between the two. Note that ViewBag is a dynamic type and not strongly typed (determined at runtime), so you’ll not have IntelliSense helping you find what’s available in the ViewBag object.

There are two more shared objects used for data transfer between Controllers and Views:

  • ViewData – essentially a dictionary where the key is a string and the value is an Object. More efficient with larger sets of data.
  • TempData – temporary data that is only persistent within the same session, and is mostly useful for preserving data only for a specific user for a specific session.

Let’s try printing out a header in our fresh HTML page from a property on the ViewBag object which we will set from the Controller.

Switch back to the Controller. In our Index method, just before we return the View, add the following line:

C#
ViewBag.MyHeader = "Hello World!";

Switch back to the View. Replace the h2 tag with the following:

ASP.NET
<h2>@ViewBag.MyHeader</h2>

Now go ahead and press F5 to start debugging. This will launch an instance of your default browser, hosted on a local instance of IIS Express. The base URL of your website would be http://localhost, followed by a random port number (by default – you may change this in the Project Properties window). Paste the following URL in the address form: http://localhost:99999/Person/Index. Replace the 99999 with the random port number you see when the browser is launched.

Image 5

ASP .NET MVC Routing

It worked! You can see that the routing is pretty intuitive – we went to the Person controller and then to the Index Action. Notice how we didn’t use PersonController as the Controller name – this is part of the ASP .NET MVC Controller naming convention. Now go back to the browser and remove the Index segment from the URL – you can see that the page still loads correctly; again, more convention over configuration – when no Action name is provided, ASP MVC’s default routing system will search for an Action called Index. This helps create cleaner, search engine friendly URLs.

You can create custom and more sophisticated routing rules by modifying the RouteConfig class under the App_Start folder.

Layout Page

Notice how our brand new View looks pretty nice without us doing any work? This is because of the Layout page. Most web applications have a consistent look throughout the website – same header, menu and footer, as well as additional items that we might want to make available site-wide. To do this in ASP .NET MVC, we use a Layout page.

The Layout page is a regular View, only it’s not associated with any Action or Controller. When you create a new View, Visual Studio will ask you if you want to associate it with a Layout page – by default this option is enabled.

By default, the Layout page is called _Layout.cshtml, and it found under the Shared folder under the Views folder. You may change this default by modifying the _ViewStart.cshtml file.

ASP.NET
@{

    Layout = "~/Views/Shared/_Layout.cshtml";

}

Open the Layout page. You’ll notice the RenderBody method is called inside an HTML div. This is where each View will be rendered.

In ASP .NET MVC 5, the default Layout page loads the Bootstrap CSS library, which means you may use it in any page which uses the Layout page. This is why the header we just added got a style which is different from the vanilla HTML style.

Creating a repository for your Model

Now let’s get back to planning our application. We need to create a repository that will store the Persons in our application. We’ll do this using Entity Framework.

This tutorial will assume that you are familiar with how Entity Framework Code First works, so go ahead and create a simple PersonManagerDbContext which contains a DbSet of Person. We will store an instance of this data context as a private field inside our PersonController, and initialize it in the constructor.

C#
private PersonManagerDataContext mDataContext;


public PersonController()

{

    mDataContext = new PersonManagerDataContext();

}

Now go ahead and populate this table with Persons (you can easily do this by creating a Console Application project, referencing the current project, and adding Person objects to an instance of the PersonManagerDbContext, then calling context.SaveChanges()).

Binding View to the Model

So now we can easily access the Persons in our database by calling mDataContext.Persons. But how do we make this available to the View?

One way would be using one of the shared objects – ViewBag or ViewData. We could add a Person property on the ViewBag and access it from the View. This approach has several problems associated with it:

  • Necessary casting – you will need to cast the properties back to string (or whatever type they are). This causes another instance of boxing and unboxing by the CLR, and is less efficient. But more importantly, it may lead to unnecessary runtime cast errors.
  • Dynamic typing – no IntelliSense is available as types are resolved at runtime. Even when using the ViewData dictionary, you cannot know at compile time if you haven’t made a typo in the key value.
  • Performance implications – In addition to the performance impact caused by the casting required, dynamic types and Dictionaries are less efficient than strong types and Collections. On smaller scales this wouldn’t be noticeable, of course.

To avoid this, we can make the model instance available to the View. To do this, open the Index view we worked on earlier, and add the following line in the top of the page:

ASP.NET
@model IEnumerable<PersonManager.Models.Person>

@model is a keyword reserved by Razor, and states the current Model type associated with this View. You can then access the instance of this Model type by using the Model keyword. Notice that capitalization, as usual with C#, matters. Model with a capital M means a call to the instance of the Model, and model represents the declaration (similar to using).

Model is strongly typed, and you can now access the properties of your model class by simply stating the property name. Obviously we want a list of all our members, so we’ve specified an IEnumerable of Persons.

Now we need to inject the Person class instance to the View. Go back to your Controller class, and modify the return statement like this:

C#
return View(mDataContext.Persons);

Note that this overload of the View method accepts an Object, so if you inject the wrong type of Model class, it will only be determined at runtime.

Here’s what happens if instead of passing an IEnumerable of Persons, we’ll pass only the first item in the collection, and then run the application and navigate to the Index Action on the Person Controller:

Image 6

Displaying the Model

Now that we have our Model available, we can build our page using Razor markup. This is what the markup looks like:

ASP.NET
@using PersonManager.Models

@model IEnumerable<PersonManager.Models.Person>


@{

    ViewBag.Title = "Persons";

}


<h2>Persons</h2>

<table class="table">

    <thead>

        <tr>

            <th>#</th>

            <th>First Name</th>

            <th>Last Name</th>

            <th>Address</th>

            <th>Phone</th>

            <th>Email</th>

        </tr>

    </thead>

    <tbody>

        @foreach (Person person in Model)

        {

            <tr>

                <td>@person.PersonId</td>

                <td>@person.FirstName</td>

                <td>@person.LastName</td>

                <td>@person.Address</td>

                <td>@person.PhoneNumber</td>

                <td>@person.Email</td>

            </tr>

        }

    </tbody>

</table>

The code is pretty straightforward: we’re statically declaring an HTML table, creating its head section, and by using a foreach statement we are dynamically creating table rows, each of which represents a Person retrieved from the database.

Note the using statement for the Person class; this is different from the model statement, and is identical to a using statement we would use in a traditional class.

Implementing Actions for adding a person

Now we’ll implement the addition of a new Person to the repository. For this we will need to create two Actions:

  • GET Action – this Action will be called by the browser initially to display the submission form to the user.
  • POST Action – this Action will be called by the form when we submit it.

But should we create two Views? Not necessarily! Only the GET Action needs to actually return a View. After submitting the form, we may just want to redirect the user back to the homepage.

Let’s implement these two Actions:

C#
[HttpGet]

public ActionResult AddPerson()

{

    return View();

}

[HttpPost]

public ActionResult AddPerson(Person person)

{

        mDataContext.Persons.Add(person);

        mDataContext.SaveChanges();

        return RedirectToAction("Index");

}

Notice how we named both Actions the same, for consistency and clearness (since one doesn’t really exist without the other). But how would ASP .NET know which Action to access in every use case? Thanks to the [HttpGet] and [HttpPost] attributes. When an HTTP GET request hits the /AddPerson route, it will be routed to the first Action, returning a View (our friendly form). An HTTP POST request will be routed directly to the second Action, which naturally accepts a Person object to add to the database.

Adding server-side validation

One of the basic rules of designing any user-oriented application is to never trust your user. We want to make sure all fields are populated with data and perform other basic tests before adding the data to our database.

We could do this by adding a series of clumsy if statements over the Person parameter, but this would be a bit tough to read. And what if we want to apply these rules again somewhere else? We’ll just repeat the code.

ASP .NET helps us with validation using the Data Validation attributes (System.ComponentModel.DataAnnotations) directly over our Model class. Feel free to explore this namespace on MSDN on your own. For now, let’s add a few of these attributes.

C#
public class Person

{

    [Key]
    [Required]
    public int PersonId { get; set; }

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

    [Required]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    public string Address { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [Display(Name = "Phone Number")]

    public long PhoneNumber { get; set; }

}

There are many more useful attributes with common rules, as well as the RegularExpression attribute, allowing you to customize the validation pattern using RegEx.

Now go back to the controller, and modify the AddPerson POST Action:

C#
[HttpPost]

public ActionResult AddPerson(Person person)

{

    if (ModelState.IsValid)

    {

        mDataContext.Persons.Add(person);

        mDataContext.SaveChanges();

        RedirectToAction("Index");

    }


    return View();

}

ModelState.IsValid will return true if the model we’ve bound to the View validates correctly against all the attributes we’ve placed. In case it doesn’t, we won’t submit the changes to the database. If the user attempts to submit this form, it will be validated first, and ASP .NET MVC will automatically display the validation errors once the View is returned (we will see how in a minute).

Finally, as you can probably understand yourself, RedirectToAction will redirect the user to the requested Action when called.

Creating a form and submitting data

Let’s go back to the AddPerson GET Action, and add a new View. Paste the following code:

ASP.NET
@model PersonManager.Models.Person


<h2>Add a new person to the database</h2>

@using (Html.BeginForm())

{

   

    <div class="form-group">

        @Html.LabelFor(model => model.FirstName)

        @Html.TextBoxFor(model => model.FirstName, new { Class = "form-control" })

        @Html.ValidationMessageFor(model => model.FirstName)

    </div> 

    <div class="form-group">

        @Html.LabelFor(model => model.LastName)

        @Html.TextBoxFor(model => model.LastName, new { Class = "form-control" })

        @Html.ValidationMessageFor(model => model.LastName)

    </div>

    <div class="form-group">

        @Html.LabelFor(model => model.Address)

        @Html.TextBoxFor(model => model.Address, new { Class = "form-control" })

        @Html.ValidationMessageFor(model => model.Address)

    </div>

    <div class="form-group">

        @Html.LabelFor(model => model.Email)

        @Html.TextBoxFor(model => model.Email, new { Class = "form-control" })

        @Html.ValidationMessageFor(model => model.Email)

    </div>

    <div class="form-group">

        @Html.LabelFor(model => model.PhoneNumber)

        @Html.TextBoxFor(model => model.PhoneNumber, new { Class = "form-control" })

        @Html.ValidationMessageFor(model => model.Email)

    </div>

    <input type="submit" class="btn btn-default"/>

}

Go ahead and run the application, then navigate to the Person/AddPerson route in your browser.

Image 7

Place a breakpoint in the beginning of the POST AddPerson method in the Person Controller, add some data to the form and submit it.

Image 8

If you add the person variable to the Watch window, you’ll be able to see the same values you’ve just entered into the form.

Image 9

Let’s take a closer look at how this magic just happened. As you can see, we’ve bound this View to the Person type (not a collection of them this time, because we only want to submit a single Person). Thanks to this, we can use ASP .NET MVC’s Form helpers.

  • Html.BeginForm() will render the form itself for us, and inject the appropriate URL for submission as the action attribute of the form tag (so that the form will know where to submit itself). By default it will assume we named the GET and POST Actions the same (again, convention over configuration), but there are overloads that allow you to name a different Action or Controller for submitting the form.
  • Html.TextBoxFor will create an input of the type text box, but the important part is that it is bound to a specified property of the Model class! When we submit the form to the server, ASP .NET MVC will inject the value of this textbox as the matching property of the Model we’re sending, so in the POST AddPerson method, we can just call person.FirstName or person.LastName and get the value the user submitted. This is done using a simple Expression accepting the type of the Model class, as you can see in the code sample.
  • Html.LabelFor will create a label HTML tag for the input tag of the same property. The default label will simply the name of the Model’s property, but you can change that by using the Display attribute over the property in the Model class (take a look at the Person class code sample before).
  • Html.ValidationMessageFor will display a validation message, according to the validation rules we’ve defined using DataAnnotations in the Person Model class.

If you don’t use Model Binding, implementing the same logic will be more cumbersome. You would need to write the html tags yourself, where the value attribute would be something like @ViewBag.MyValue. This is not a recommended approach.

Adding HTML attributes in ASP .NET MVC HTML helpers

Many of ASP .NET MVC’s HTML helpers generate handy HTML for us, but what if we want to customize the HTML? (for example, add a class attribute to style a Text Box created by the TextBoxFor helper)

We can do this quite simply, by using an overload of the helper which accepts an Object containing the HTML attributes we want to add. Take a look at the example above. I’ve created an object which only contains a string property named Class – which ASP .NET MVC will add as a Class attribute. You can add any type and combination of HTML attributes, even non-standard ones (such as ones used for jQuery data manipulations and such).

Adding client-side validation

Remember us saying ‘never trust the user’? While this is true, we also don’t want to make the user send the form to the server and wait for a response only to realize he had forgotten one field. We also want to avoid this unnecessary traffic to the server.

This is where client-side validation comes to play. There are various ways of implementing this, either via HTML 5 (which is only supported in modern browsers) or via libraries such as jQuery (which has wider support).

ASP .NET MVC has a cool feature which automatically implements jQuery client-side validation using the rules that we have set up using the DataAnnotations attributes. This allows us, again, to define the validation rules in only one place.

Note that client-side validation should never be trusted on its own, because if JavaScript is disabled in the user’s browser, it won’t trigger. You should always have server-side validation.

To do this, you need to install the NuGeT package called Microsoft jQuery Unobtrusive Validation. After the installation has finished, add it as a Bundle to the BundleConfig.cs file, like this:

C#
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(

                "~/Scripts/jquery.validate*"));

Bundles are another unique ASP .NET MVC concepts, and are essentially groups of scripts or other types of files – as some JavaScript libraries and frameworks come in several different files. In this case we’ve created a package which collects all files in the Scripts folder that contain jquery.validate (note the asterisk).

Now go to the Layout page and at the bottom of the page add this line:

C#
@Scripts.Render("~/bundles/jqueryval")

This will render the HTML with the <script> tag linking to all scripts in the Bundle.

And that’s all you need to do. If you reload and view the source of the HTML page, you’ll see something like this:

Image 10

The data-* attributes are special attributes added by ASP .NET MVC, and are parsed by jQuery in order to perform validation. You can customize the error message displayed by providing an argument to the DataAnnotation attribute on your model class (see the example). This will, again, affect both client and server validation.

What's next?

This is the end of this basic ASP .NET MVC tutorial, but there’s much more to learn about this framework. I haven’t included these subjects in the tutorial so the examples don’t get overwhelming and hard to understand, but I encourage you to read more about these topics:

  • Partial Views
  • Different types of ActionResults (what you return from your Action) – especially JsonResult
  • Authorization & Authentication (Windows & Individual User Accounts)
  • Web API (technically, not exactly a part of ASP .NET MVC, but closely related)

License

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


Written By
Software Developer
Israel Israel
Software Developer specializing in .NET, Web Development and Software Test Automation.

Comments and Discussions

 
PraiseThanks Pin
mlanca2-Oct-21 8:01
mlanca2-Oct-21 8:01 
QuestionError Pin
Member 131936347-Jun-17 4:48
Member 131936347-Jun-17 4:48 
QuestionMy Vote 5 Pin
Amit Jadli4-Nov-15 18:52
professionalAmit Jadli4-Nov-15 18:52 
QuestionGood Article Pin
Dharmesh .S. Patil24-Jun-15 20:28
professionalDharmesh .S. Patil24-Jun-15 20:28 
QuestionHTTP 404 Pin
Roger C Moore24-Apr-15 5:46
Roger C Moore24-Apr-15 5:46 
AnswerRe: HTTP 404 Pin
Roger C Moore24-Apr-15 9:53
Roger C Moore24-Apr-15 9:53 
QuestionNice Article Keep Going Pin
chandruvelan15-Apr-15 19:02
chandruvelan15-Apr-15 19:02 
QuestionMessage Closed Pin
11-Oct-14 21:37
Member 802661711-Oct-14 21:37 
GeneralASP.NET MVC Development Company Pin
Aum InfoTech27-Aug-14 2:51
Aum InfoTech27-Aug-14 2:51 
QuestionCorrection Pin
Arjunwalmiki6-Jun-14 1:43
Arjunwalmiki6-Jun-14 1:43 
GeneralMy vote of 5 Pin
Renju Vinod14-May-14 21:27
professionalRenju Vinod14-May-14 21:27 
QuestionMove Images Pin
thatraja5-May-14 0:21
professionalthatraja5-May-14 0:21 
QuestionIllustrative! Pin
RahulMGunjal29-Apr-14 21:55
RahulMGunjal29-Apr-14 21:55 
GeneralNice Article! Pin
Ravimal Bandara29-Apr-14 2:46
Ravimal Bandara29-Apr-14 2:46 
GeneralGood article... Pin
Dnyaneshwar@Pune28-Apr-14 3:30
Dnyaneshwar@Pune28-Apr-14 3:30 

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.