ASP.net MVC for Begginners in Web

22
Search for articles, questions, tips Q&A forums lounge articles Rate this: Tal Bronfer, 29 Apr 2014 CPOL ASP .NET MVC for Beginners in Web Development 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. 4.85 ﴾53 votes﴿ 11,765,758 members ﴾56,044 online﴿ Sign in

description

ASP .NET MVC for Beginners in Web Development

Transcript of ASP.net MVC for Begginners in Web

Page 1: ASP.net MVC for Begginners in Web

1443031750582.265 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 1/22

Search for articles, questions, tipsQ&A forums loungearticles

Rate this:Tal Bronfer, 29 Apr 2014 CPOL

ASP .NET MVC for Beginners in Web Development

Introduction to ASP .NET MVC 5 for .NET developers that are completely new to Web development, MVC frameworks and WebApplication Frameworks in general.

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

PrerequisitesHTML – basic skills ﴾structure of a web page, tags﴿CSS – basic skills, including basic familiarity with the Bootstrap frameworkC# ‐ you should be fully comfortable writing C# applications, and be familiar with the following features:

LINQAnonymous TypesExpressions

.NET Framework libraries – you should be familiar with popular framework features, such as:

Entity Framework Code First ﴾basic﴿Dynamic variables

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

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 WebTools 2013.1 for Visual Studio 2012 package, whereas the examples will be based on ASP .NET MVC 5. That’s okaythough, as the differences between the versions are mainly in authentication features and not in syntax.

   4.85 ﴾53 votes﴿

11,765,758 members ﴾56,044 online﴿ Sign in

Page 2: ASP.net MVC for Begginners in Web

1443031750859.335 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 2/22

What are Web Application Frameworks?Put simply, Web Application Frameworks allow you to create applications which generate HTML pages ﴾typically, though thereare other types of responses which we will brush on later﴿ dynamically, rather than storing pre‐created HTML pages on yourweb 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 WebApplication 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 WebApplication frameworks such as Ruby on Rails, Django and Zend Framework. MVC is commonly used to structure user‐orientedapplications ﴾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 intothe 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 typicalModel class would only include ‘dumb’, public properties. For example, for the Person model you would include the followingproperties:

NameAddressEmailPhone

Other components of MVC will use the Model classes to perform logic ﴾for example, add a Person to a database﴿ and to displayit 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 perfectlynormal to have a Person Model class that is used internally in your application, in the server side ﴾for example, processing creditcard 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 canalso 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 notstored 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 allthe Persons in our application, the controller class will contain the code which accesses the database, queries it for theappropriate user set, and then creates a View with the given Model ﴾which would be a list of the Persons returned from thedatabase﴿.

Page 3: ASP.net MVC for Begginners in Web

1443031751139.137 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 3/22

Each controller exposes a set of public methods, called Actions. This is your application’s API. Each View is associated with asingle 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 evennecessarily 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, ifour 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 likehttp://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 Idparameter 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 theseconventions, 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 MVCFramework.

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 theconfusion﴿. 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 littleto no code at all, using controls from the Toolkit. However, Web Forms doesn’t enforce modern design patterns, maysometimes 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 sourceMVC 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 ownlogic, and creates clean, compatible HTML pages and application logic that is easily testable. It does, however, require a steeperlearning curve and generally speaking, more code.

Your First ASP .NET Application - PersonManager

Creating a new ASP .NET MVC application

Page 4: ASP.net MVC for Begginners in Web

1443031751357.763 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 4/22

Our first application will be very simple: it will load a set of users from a database using Entity Framework, and display them tothe 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 VisualStudio Express for Web, you will immediately see this project option when creating a new project.

In this case, choose the MVC option, then click the Change Authentication button and choose No Authentication. In earliereditions of Visual Studio, this screen may look a bit different. Be sure to uncheck any additional options if they exist in youredition. 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 complexconfiguration 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 theApp_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 –

Page 5: ASP.net MVC for Begginners in Web

1443031751619.25 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 5/22

person. Let’s create that class in the Models folder.

Hide   Copy Code

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 theControllers folder and then Add ‐> Controller. In the scaffolding dialog which shows, choose MVC 5 Controller.

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

Page 6: ASP.net MVC for Begginners in Web

1443031751809.951 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 6/22

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.

Hide   Copy Code

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 callsthe View method without any parameters﴿. This association is created by another instance of convention over configuration. Ifyour Action is called Index, ASP .NET MVC will automatically look for a View called Index ﴾you can name it differently, and use anoverload of the View method which accepts a View name﴿. Go ahead and create a new View by right‐clicking within the IndexAction, then clicking Add View.

Page 7: ASP.net MVC for Begginners in Web

1443031752020.924 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 7/22

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

Let’s take a look at the result.

Hide   Copy Code

@{

    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 engineis 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 maydo the following:

Hide   Copy Code

<ul>

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

Page 8: ASP.net MVC for Begginners in Web

1443031752241.018 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 8/22

    {

        <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 blockof 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 indicatethat 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 eitherway. 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 @usingstatement 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 thedata from the Controller for textual representation. Code that interacts with the data, performs calls to external resources or canbe ﴾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 databetween the two. Note that ViewBag is a dynamic type and not strongly typed ﴾determined at runtime﴿, so you’ll not haveIntelliSense 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 ofdata.TempData – temporary data that is only persistent within the same session, and is mostly useful for preserving data onlyfor 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 theController.

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

Hide   Copy Code

ViewBag.MyHeader = "Hello World!";

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

Hide   Copy Code

<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 instanceof IIS Express. The base URL of your website would be http://localhost, followed by a random port number ﴾by default – youmay 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.

Page 9: ASP.net MVC for Begginners in Web

1443031752450.479 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 9/22

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 namingconvention. Now go back to the browser and remove the Index segment from the URL – you can see that the page still loadscorrectly; again, more convention over configuration – when no Action name is provided, ASP MVC’s default routing system willsearch 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 webapplications have a consistent look throughout the website – same header, menu and footer, as well as additional items that wemight 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, VisualStudio 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 maychange this default by modifying the _ViewStart.cshtml file.

Hide   Copy Code

@{

    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 berendered.

In ASP .NET MVC 5, the default Layout page loads the Bootstrap CSS library, which means you may use it in any page whichuses 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.

Page 10: ASP.net MVC for Begginners in Web

1443031752679.122 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 10/22

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

Hide   Copy Code

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 callingcontext.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 availableto the View?

One way would be using one of the shared objects – ViewBag or ViewData. We could add a Person property on the ViewBagand 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 anotherinstance of boxing and unboxing by the CLR, and is less efficient. But more importantly, it may lead to unnecessaryruntime 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 andDictionaries 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, andadd the following line in the top of the page:

Hide   Copy Code

@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 theinstance of this Model type by using the Model keyword. Notice that capitalization, as usual with C#, matters. Model with acapital 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 statementlike this:

Hide   Copy Code

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 bedetermined at runtime.

Page 11: ASP.net MVC for Begginners in Web

1443031752900.79 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 11/22

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

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:

Hide   Shrink   Copy Code

@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>

Page 12: ASP.net MVC for Begginners in Web

1443031753068.777 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 12/22

                <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 foreachstatement 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 statementwe 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 theform, we may just want to redirect the user back to the homepage.

Let’s implement these two Actions:

Hide   Copy Code

[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.

Page 13: ASP.net MVC for Begginners in Web

1443031753285.284 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 13/22

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 thedatabase.

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 arepopulated 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 overour Model class. Feel free to explore this namespace on MSDN on your own. For now, let’s add a few of these attributes.

Hide   Shrink   Copy Code

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 customizethe validation pattern using RegEx.

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

Hide   Copy Code

[HttpPost]

public ActionResult AddPerson(Person person)

{

    if (ModelState.IsValid)

    {

Page 14: ASP.net MVC for Begginners in Web

1443031753492.934 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 14/22

        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’veplaced. In case it doesn’t, we won’t submit the changes to the database. If the user attempts to submit this form, it will bevalidated first, and ASP .NET MVC will automatically display the validation errors once the View is returned ﴾we will see how in aminute﴿.

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:

Hide   Shrink   Copy Code

@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" })

Page 15: ASP.net MVC for Begginners in Web

1443031753656.799 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 15/22

        @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.

Page 16: ASP.net MVC for Begginners in Web

1443031753880.622 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 16/22

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

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.

Page 17: ASP.net MVC for Begginners in Web

1443031754072.396 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 17/22

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 acollection of them this time, because we only want to submit a single Person﴿. Thanks to this, we can use ASP .NET MVC’s Formhelpers.

Html.BeginForm() will render the form itself for us, and inject the appropriate URL for submission as the action attributeof the form tag ﴾so that the form will know where to submit itself﴿. By default it will assume we named the GET and POSTActions the same ﴾again, convention over configuration﴿, but there are overloads that allow you to name a differentAction 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 propertyof the Model class! When we submit the form to the server, ASP .NET MVC will inject the value of this textbox as thematching property of the Model we’re sending, so in the POST AddPerson method, we can just call person.FirstName orperson.LastName and get the value the user submitted. This is done using a simple Expression accepting the type of theModel 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 nameof 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 usingDataAnnotations 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 tagsyourself, 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 wewant to add. Take a look at the example above. I’ve created an object which only contains a string property named Class – whichASP .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 serverand 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 onlysupported 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 setup 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, itwon’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 hasfinished, add it as a Bundle to the BundleConfig.cs file, like this:

Page 18: ASP.net MVC for Begginners in Web

1443031754253.495 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 18/22

Hide   Copy Code

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 someJavaScript libraries and frameworks come in several different files. In this case we’ve created a package which collects all files inthe 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:

Hide   Copy Code

@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:

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 includedthese subjects in the tutorial so the examples don’t get overwhelming and hard to understand, but I encourage you to readmore about these topics:

Partial ViewsDifferent types of ActionResults ﴾what you return from your Action﴿ – especially JsonResultAuthorization & Authentication ﴾Windows & Individual User Accounts﴿Web API ﴾technically, not exactly a part of ASP .NET MVC, but closely related﴿

LicenseThis article, along with any associated source code and files, is licensed under The Code Project Open License ﴾CPOL﴿

Share

About the Author

EMAIL TWITTER

Page 19: ASP.net MVC for Begginners in Web

1443031754545.981 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 19/22

Search Comments   Go

 

You may also be interested in...

Classic ASP and MVC Developer Tips for Scanning onthe Web

MVC on Azure for Beginners Scan Anything, Anywhere, AnyTime

First MVC Application forBeginners

Getting Started with the Intel®Edison Board on Windows

Comments and Discussions

You must Sign In to use this message board.

First Prev Next

Tal BronferSoftware DeveloperIsrael

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

Page 20: ASP.net MVC for Begginners in Web

1443031754802.662 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 20/22

I give my 5

Sign In · View Thread · Permalink

When I attempt to press F5 under your section "ViewBag" this is what I get:

Hide   Copy Code

Server Error in '/' Application. The resource cannot be found.   Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.   Requested URL: /Views/Index.cshtml 

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34248 

Do you have any suggestions? What am I missing? TIA.

Sign In · View Thread · Permalink

OK, got it, this is the URL I need to access, say:

http://localhost:52101/Person/Index[^]

Sign In · View Thread · Permalink

Nice Artical Keep going

Sign In · View Thread · Permalink

Good ArticleDharmesh .S. Patil 24‐Jun‐15 20:28

HTTP 404john_1726 24‐Apr‐15 5:46

Re: HTTP 404john_1726 24‐Apr‐15 9:53

Nice Article Keep Goingchandruvelan 15‐Apr‐15 19:02

Beginner ASP.NET MVC TutorialsMember 8026617 11‐Oct‐14 21:37

Page 21: ASP.net MVC for Begginners in Web

1443031755008.048 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 21/22

Beginner ASP.NET MVC Tutorials...

Beginner ASP.NET MVC Tutorialshttp://studyoverflow.com/asp‐mvc

Sign In · View Thread · Permalink 1.00/5 ﴾1 vote﴿

This is the very nice article. MVC gives so much security.If anyone want to any asp.net mvc development company, i can recommend AUM InfoTech.

Sign In · View Thread · Permalink

pls correct the line of codeHide   Copy Code

<div class="form‐group">        @Html.LabelFor(model => model.PhoneNumber)        @Html.TextBoxFor(model => model.PhoneNumber, new { Class = "form‐control" })        @Html.ValidationMessageFor(model => model.Email)    </div>

from toHide   Copy Code

<div class="form‐group">        @Html.LabelFor(model => model.PhoneNumber)        @Html.TextBoxFor(model => model.PhoneNumber, new { Class = "form‐control" })        @Html.ValidationMessageFor(model => model.PhoneNumber)    </div>

Sign In · View Thread · Permalink

Nice

ASP.NET MVC Development CompanyAum InfoTech 27‐Aug‐14 2:51

CorrectionArjunwalmiki 6‐Jun‐14 1:43

My vote of 5Renju Vinod 14‐May‐14 21:27

Page 22: ASP.net MVC for Begginners in Web

1443031755212.68 ASP .NET MVC for Beginners in Web Development ­ CodeProject

http://www.codeproject.com/Articles/765519/ASP­NET­MVC­for­Beginners­in­Web­Development 22/22

Permalink | Advertise | Privacy | Terms of Use | Mobile Web02 | 2.8.1509020.2 | Last Updated 29 Apr 2014

Article Copyright 2014 by Tal BronferEverything else Copyright © CodeProject, 1999‐2015

Layout: fixed | fluid

Sign In · View Thread · Permalink 5.00/5 ﴾1 vote﴿

Host the images on Codeproject which is best option. I can't see the images now. The reason is simple .... Imagehosting websites blocked by most of the workplaces. So better move images.

thatraja

Code converters | Education Needed | Improve EverythingNew

Sign In · View Thread · Permalink

Nice article with good details

Sign In · View Thread · Permalink

Nice article. Keep writing!

Sign In · View Thread · Permalink

Good article...

Sign In · View Thread · Permalink

Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Rant    Admin   

Move Imagesthatraja 5‐May‐14 0:21

Illustrative!RahulMGunjal 29‐Apr‐14 21:55

Nice Article!Ravimal Bandara 29‐Apr‐14 2:46

Good article...Dnyaneshwar@Pune 28‐Apr‐14 3:30