Click here to Skip to main content
13,771,597 members
Click here to Skip to main content
Add your own
alternative version

Stats

12.2K views
231 downloads
26 bookmarked
Posted 22 Mar 2017
Licenced CPOL

Create Desktop UX With ASP.NET MVC (Part 1 of 3)

, 22 Mar 2017
Rate this:
Please Sign up or sign in to vote.
Part 1: Master the ASP.NET MVC Project Template & Technologies (Razor, jQuery, JavaScript, Bootstrap, CSS). Part 2: Build an ASP.NET MVC app which runs in the browser but feels like using a desktop app.

Introduction

As apps have progressed toward running in the browser users have lost some of the intuitive functionality that the desktop provides.  Here, I am specifically thinking about Windows Forms as objects the user interacts with and the associated ContextMenus which provide the ability to right-click an element to learn more about options that are available on the item. 

The following animated gif provides an idea of what we're driving towards.  (This basic UX functionality is complete by the end of the Part 2 of this series -- Create Desktop UX With ASP.NET MVC (Part 2 of 3)[^]).

Article In Two Three Parts : How This Will Work

I've broken this article into two three parts in an effort to allow you to focus on each part of the development.

Part 1 : Beginner's Guide to Creating an MVC App From Nothing

We start with the Visual Studio ASP.NET MVC Empty template and only add what we need.  

You will learn about each piece we add in isolation and learn why there are so many different technologies involved and how ASP.NET MVC brings them all together.  ASP.NET MVC can be quite overwhelming because of the number of moving parts.  

Part 1 of this article will guide you through why things are included in ASP.NET MVC while discovering the underlying MVC Application Framework.

Part 1 : Deep Dive Into ASP.NET MVC Workings

We will create our application foundation all while diving deeply into the reasons why we add each piece.

By the time you finish this article you own the knowledge of:

  • Which MVC template should I choose and which options?
  • Understand MVC Project Structure - what are all of those folders and what do you put in each
  • What happens when I create an empty project, build & run? An error, but what does it mean?
  • Why do I need to add a Controller to the project first?
  • Basically, what is a Controller?
  • How do I easily add an associated View?
  • What is _ViewStart and should I use it?
  • Where does all that template HTML come from?
  • What is _Layout.cshtml and how is it related to the Layout App variable?
  • Wht are MVC Routes and how do they work?
  • What are those funny @{ } things in my HTML and exactly what do they do? Razor View Engine Directives
  • Why do I sometimes just see @Things in my HTML with no brackets?
  • Where does the basic MVC app get its styles?  Where is the CSS and how do I change it? (Bootstrap)
  • Which JavaScript libraries does MVC automatically include and how do I use them? (Bootstrap, jQuery, Modernizr)
  • Bootstrap.JS and Bootstrap.CSS? Yes, Two Different Sides of Same Coin
  • Where should I put my JavaScript and how do I load my JS files properly within the MVC context?
  • JavaScript IIFE (Immediately Invoked Function Expression)
  • Running scripts after HTML loads - jQuery ready() method

If you've already build ASP.NET MVC apps and you know all about how they work, feel free to skip Part 1.

Part 2 : Building the Reusable Context Menu App

Part 2 will be a deep dive into the specific code you need to create a reusable ASP.NET MVC application which creates a desktop user experience (UX).  You will see JavaScript, jQuery, Bootstrap, Razor, CSS and C# code you will need to create Windows Form-like objects that implement a ContextMenu that works just as it does in a desktop app.  I agree that it's a lot of different technologies to do this work but we will isolate our work on each as much as possible so you can gain a strong understanding of each.   By the end of the article you will understand each line of code added to the project.

Part 3: Building the Client / Server Interaction

In part three we will build the code that completes the app functionality as we learn how the Context Menu will fire AJAX calls to the server.  We will also learn how to use the Controller to receive the requests and build PartialViews which are rendered as separate windows on my SPA (single page app).

Background

Over a year ago I created a prototype application using ASP.NET MVC.  It was a simple app that was supposed to allow the user to query for data and see results.  However, I wanted to make using the app as intuitive to desktop users as possible and I came up with something that ended up having a look and feel of a desktop app.  Since it was a prototype I wanted to return to it, clean up the code and make it a bit more reusable.  Hopefully you'll find this an interesting entry into ASP.NET MVC. I believe you'll find you can reuse and customize this code for use in your own apps.

Part 1 : Overview of Steps & Topics

Here are all of the steps we are going to walk through to get a strong foundation of understanding about how ASP.NET MVC apps work.

  1. Create a blank ASP.NET MVC project
  2. add a new home controller -- allow it to add the default actions.
  3. right-click the Index() action's view and add a new View
  4. Add new javascript file to Scripts directory, name it contextMenu.js
  5. Examine Site.css and where styles come from.

Now, I'll walk you through all of those steps and include screenshots so you can see exactly what it'll look like to do this work in Visual Studio.  I'll be using Visual Studio 2013 but it will be very similar in 2015.

Create Blank MVC Project

Start up Visual Studio and create a new project.

Choose the Visual C#...Web...from the treeview side and then choose the ASP.NET Web Application as shown in the image and click the [OK] button.

new blank mvc project

A new dialog box will appear and here you need to make it match exactly what you see in the following image.

blank proj with mvc, webapi

You want to choose the blank project but also "Add folders and core references for" MVC and WebAPI.

You can certainly add the Unit Tests too if you like, but for this article I will not, simply to make the article shorter.

Make sure all the other settings are just as they are shown in the previous screenshot and click the [OK] button.

When you do, Visual Studio will create the new project based upon the template selections you have made.

Visual Studio should display the project folders and files in the Solution Explorer.  Even thoug this is an "empty project" it still contains quite a few things (folders, global.asax, web.config, etc). 

Build Empty Solution

If you build the empty solution, it will succeed.  However, running the applicaton will fail.  Let's try it now just so you can have an idea of what we are doing in the next step.  When you build and run you will see something like the following in your web browser:

404 error

That occurs because there is no handler (Controller) for the route (/) that the user attempted to access.  In other words, our MVC app has nothing to use to generate HTML output for the user so it returns a 404 error (resource not found).   

A slight clue to this problem can be found by looking in the RouteConfig.cs file which is found in the App_Start folder.  That file has a RegisterRoutes method that sets up default paths that are valid in our application.  

The RegisterRoutes method looks like the following:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

The bolded line creates the default route.  The default route looks for a controller named Home which contains an Action (method) named Index.

By convention an MVC app expects the route to find a Controller - the home controller in our case.  Of course we do not have any controllers included in our app yet.  Let's add our first one.

Add A New Controller

Right-click the Controllers folder and choose Add => Controller... from the context menu which appears, as shown.

add controller

A large dialog box with quite a few choices appears.  We want a relatively simple controller, however I don't want it to be completely empty so I'll let the Visual Studio template create some basic read/write actions.  Go ahead and choose the second choice as shown and click the [Add] button.  Note: I've cropped off some of these windows because they are so large.

add controller with read/write

When you click the [Add] button another dialog box will popup asking you to name the controller.

name the controller

ASP.NET MVC Conventions

ASP.NET MVC uses Convention Over Configuration. That simply means that it follows some basic process patterns so you don't have to configure everything.  However, that means you learn the process patterns.  In this case, Visual Studio tries to help you by highlighting the portion of the controller name that you should rename.  

Visual Studio Conventions : Controller & View

In ASP.NET MVC the convention is that controllers are named <name>Controller and Views are named <name>View where <name> is a value provided by the developer.  Further, the <name> will also be the same for Controllers and their matching Views.  

HomeController Will Have HomeView

So, we are going to name our first Controller the HomeController and later you will see a View named HomeView will be added.  Go ahead and change the name and click the [Add] button.

homecontroller

When you add the new Controller, Visual Studio will generate and display the HomeController.cs file.

display of view file

You can see in Solution Explorer that Visual Studio has added the new file (HomeController.cs) to the Controllers folder.  Also notice that the View() methods are currently in red text in the editor.  That's because they have not yet been implemented anywhere.  We'll fix that in a moment by adding a view, but first let's take a look at what happens if we build and run right now.

Build & Run Without A View

Go ahead and build and run the project.  When you do you will see something like the following:

view not found

Get Comfortable With Error Messages

At first you might think that is just a bunch of nonsense.  However, it is important to know what the MVC application is trying to tell you when this happens.  It's important, because if you're going to spend any time at all developing MVC apps you are going to run into this error message sooner or later.  That's because if you have a working MVC application and a View gets accidentally deleted or isn't migrated you will see this error.

What Is A Matching View?

As you can see, the MVC framework is trying to warn you that it searched certain places (places it looks by convention) for a view, but it did not find a matching one.  

The clue to the View the framework is trying to find is in the error message at the top:

 

MVC Framework:
The view 'Index' or...

This is a clue that the Controller was searching for a matching view named Index and could not find it.

That's because we have not added a valid View to match our HomeController.  Again, this is all related to the default route that is in the RegisterRoutes method that runs when the MVC app starts.

Now, let's add a new View which will solve this problem.

Add A View

Visual Studio is very helpful with adding views.  From the editor where you have the HomeController open, you can right click inside the Index() method or on the first line of the Index() method and a context menu will appear.

When that menu appears, choose the [Add View...] menu item.

add view

When you make that selection the Add View dialog box will appear.  

add view dialog

The Index is the correct name for our view so we will accept that and all of the default values by clicking the [Add] button.  However, before we do that, notice that the [Use a layout page] checkbox is selected even though there is no layout selected.  That is indicating that we want a default layout and we'll see more about that as we progress through this article.

Go ahead and click the [Add] button now and Visual Studio will create a few files for us.

Once Visual Studio is done generating the files it will open the Index.cshtml file in the editor.

The view file is very small (only contains four lines of code), but we can now successfully run the app.

All Code For Index.cshtml 

Here's the entire code listing that shows up in your editor:

all code for view

Build & Run : Basic View

Go ahead and build and run again and you will now see a very basic page in your web browser.

most basic mvc app

Even though the web page is so basic, it still almost seems like magic since it's difficult to determine where the HTML came from that creates the output.

Where's the Basic HTML Structure?

First of all, where is the basic required HTML structure of the HTML, HEAD, BODY, and other tags that you know are required for an valid HTML document?

Layout and ViewStart Magic

Remember back there when we created the view on the Create View dialog we accepted that extra checkbox which was labeled [Use a layout page]?  That choice actually created two additional files for us in addition to the Index.cshtml file.  You can see them more clearly in the Solution Explorer under the Views folder.

solution explorer view files

You can see that we now have two new folders under our Views folder (Home and Shared) and we have three new files that were created:

  1. Home\Index.cshtml
  2. Shared\_Layout.cshtml
  3. _ViewStart.cshtml

_ViewStart.cshtml

This is a special file that the MVC framework looks for when the application starts.  When it is found, then the application will follow its directives to load other files.  Of course, if it's not found that's fine.  Our _ViewStart.cshtml has very little in it but it does provide us with another clue about where all the HTML might be found.  It points to another file that was generated by Visual Studio when we created our initial view.

You can learn the intimate details of how _ViewStart.cshtml gets loaded by the RazorViewEngine in my other article here at CP : Razor: Secrets of the MVC ViewEngine Exposed[^]

viewstart code

_Layout.cshtml

The _Layout.cshtml is a template HTML file which will be used in a site-wide nature (this is why it is in the Shared directory).  

Examining this file is far more rewarding because we finally find the required HTML tags that we know we need for valid HTML.  This file represents the base structure of our web site at this point.  However, the entire file is only 40 lines.

** This is the place where we will want to put any HTML that we want to show up on all of our pages.  **

Note: This is the perfect location for the HTML which will represent our ContextMenu since we will want it to be available to us from anywhere within our application.

Here's a quick view of the entire file since we will be working with this file.

layout.cshtml code

More About _ViewStart.cshtml

We will talk more about what is going on in the _Layout.cshtml but first let's talk about those three odd lines which make up the entire _ViewStart.cshtml file.

Razor View Engine Directives

The code in _ViewStart.cshtml is a Razor View Engine directive.  It is specialized template code that the MVC framework knows will be consumed by the Razor View Engine.  We write code like this to get the Razor View Engine's attention.  The directive is in our HTML file (named cshtml to indicate that it can contain C# code that the Razor View Engine can consume).

Razor View Engine Compiles Code

When the MVC framework sees the special characters @{ } it knows that is its cue to get the Razor View Engine involved.  Once it recognizes the directive it understands that the code in between will be C# code.

Web Browsers Cannot Compile or Run C#

Obviously, web browsers don't compile or run C# code.  However, the web browser never sees this code.  Instead the Razor View Engine compiles the code and follows the directive to run C# code on the server side.

In the case of our very basic _ViewStart.cshtml there is only one line of code.

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

That line of code sets a application global variable named Layout to a string representing the HTML structure that wil be used on every page that displays within your ASP.NET MVC web app.

Built-In ASP.NET MVC Variables

Layout is a built-in ASP.NET MVC variable which is created for your use by the ASP.NET MVC application.  That's why it feels like magic, as if the variable appears out of nowhere.  It is a part of the application framework which your web application runs within.

Inline Code Using Just the @ Symbol

As I said earlier, the special characters @{ } indicate that the lines between will be C# code.  However, if you have a single line of code you want to run or you want to get the value of a variable you can simple prefix it with a @ symbol.  

There's a good example of this in the _Layout.cshtml file in the head section.  You can see a line of code that looks like the following:

<title>@ViewBag.Title - My ASP.NET Application</title>

The important part here is the @ViewBag.Title which is a directive to the Razor View Engine that it should get the value of the @ViewBag variable (a dynamic collection object) and find the property named Title, retrieve the value and render it in this exact spot.  That makes our page title to be whatever String is in that property plus the rest of the normal characters shown ( - My ASP.NET Application).

You may be wondering, "where is the @ViewBag.Title set?  Look back at the top of your Index.cshtml file and you'll see a Razor View Engine directive block at the top that looks like:

@{

    ViewBag.Title = "Index";
}

That is where the value gets set.  That means when your Index.cshtml file is rendered it will set the page's title text to : Index - My ASP.NET Application

This little section has really opened up a lot of knowledge about the inner workings of ASP.NET MVC.  But, wait, there's more.  :)

We can coerce Visual Studio's Intellisense to show us more of these ASP.NET MVC variables by typing code in the right place.

Coercing Visual Studio Intellisense

Open up your Index.cshmtml file in the Visual Studio editor.  Move down under the directive block so you are not inside the brackets and type :

<p>  At this point, the editor should fill in the closing </p> for you and your cursor will be between the tags.  That will just help us when we run the code.  Now type a @ symbol and Intellisense will popup.

Note: Later I noticed that this intellisense is actually created by my Resharper instance.   Those won't exactly show up using just Visual Studio and that's unfortunate.

Intellisense Razor directives and vars

Do you see that last item? It's the application's global Layout variable.  Isn't that cool?  We are revealing a bunch of objects and variables that are available to use via Razor directives.

Let's add a few and run the web app just to see what will be displayed.

I changed my Index.cshtml file so it looks like the following:

@{
   
    ViewBag.Title = "Index";
}
<p>@Layout</p>
<p>@App</p>
<p>@IsAjax</p>
<p>@IsPost</p>
<h2>Index</h2>

Again, I've placed these between <p> tags just so we'll get line breaks.  When you run that you'll get something which looks like the following:

global app vars revealed

The first line shown represents that string we originally saw being set in the _ViewStart.cshtml file.  The second line is the name of the class that represents the Application object.  The third one is false since this wasn't an Ajax request.  And the last one is false because the page was retrieved via HTTP Get and not a Post.  

This knowledge will carry you far in your MVC application development.  Now, let's see how we use the other elements of the application framework to create our custom apps.

JavaScript & CSS

Now that you understand a lot of what is going on in the underlying ASP.NET MVC framework you are ready to learn how to begin to add your own custom JavaScript and how to alter CSS styles in the application. After that, you'll be ready to jump into Part 2 of this article.

Default Libraries

By default, the MVC project template adds a few JavaScript libraries to our project. To see all of the libraries included, take a look at Solution Explorer and open up the Scripts folder.

Scripts directory

Understand Minified JavaScript

The first thing to understand is that there are duplicate JS files in the directory.  That's because, for example the bootstrap.js and bootstrap.min.js files are really the same file, except the one which includes min in its name is a minified version.  That simply means it was put through a process which strips out extraneous spaces and in some cases renames variables so they are shorter.  This makes the resulting JS file much smaller and provides two benefits :

  • faster transmission
  • obfuscated code (for a slight bit of secrecy)

The obvious issue is when you have to step through any of the JavaScript because of a bug.  In those cases you do not want to look at the minified version.  Here is a sample of the regular bootstrap.js compared to the bootstrap.min.js. The regular one is on the left of the red line and the minified is on the right.

js regular and min

That means in actuality we only have three different JavaScript libraries in the project:

  • jQuery
  • Bootstrap
  • Modernizr

In this project we will only be using the jQuery library directly (making calls to jQuery methods from our JavaScript).  The Bootstrap.js is used in certain places along with the Bootstrap.css file but for the most part we won't need to leverage the Bootstrap functionality either.  

Bootstrap JS & Bootstrap CSS : Two Different Things

It's easy to confuse the Bootstrap JavaScript with the Bootstrap CSS styles, but they are really two different things.  The Bootstrap devs just noticed that there are some things they could only do via JavaScript so they added a helper file for those things.

 Of course, we will be indirectly using the Bootstrap.css styles but we'll talk about that later in this article.

Where Do the JavaScript Libraries Get Loaded?

To understand where the libraries actually get loaded for our use, we need to take a look at the _Layout.cshtml file again.  We now understand that this file will be loaded for every page in our app (since _ViewStart.cshtml sets the global Application variable Layout to point at it).

There are two places where the libraries are actually loaded.

Loading JavaScript : It's Place In HTML

Generally, there are two places where JavaScript is loaded on any web page (this is not just limited to ASP.NET MVC but to basically all web pages):

  • top of HTML web page: generally inside the <head> tag
  • bottom of HTML web page: generally the last item before the closing </body> tag

The reasons for this are:

  1. Loading from the <head> tag is basically a hold-over to the old days of HTML and how web pages were loaded. Placing the JavaScript in the <head> tag was an attempt to insure the JavaScript was loaded and ready by the time the page rendered.  That way the functions and values would be available from the HTML DOM elements.
  2. Bottom of page (right before closing </body> tag is used more frequently now because the page onLoad() method is generally the signal that the page is loaded and now the JavaScript code can run since all of the HTML DOM elements will be available.  
IIFE, jQuery Ready, etc

There are numerous ways now to handle this load order thing now such as using the jQuery.Ready method which fires when the document is done loading, so most of this is just moot.  You should still understand how this works.  This can also be solved using an IIFE (Immediately Invoked Function Execution) method and that is what you will see in our code. 

You will see that both locations are used in the _Layout.cshtml file.

Let's add our new JavaScript file and get it to do something once the page is done loading so we can insure our applicaton framework works as expected.

Add Our New JavaScript File

Visual Studio makes this very easy.  Since we are going to add our JavaScript file in the same folder with the others just right-click the JavaScript folder in the Solution Explorer and choose the Add => JavaScript File... menu item.

add new js file

A dialog box will appear and you type the name of your JavaScript file in and press the [OK] button.  You do not have to include the file extension since it knows it is a .js file. You supply just the base name. In our case we are naming it ContextMenu.

contextmenu js file

When you click the [OK] button Visual Studio will create the file in the Scripts directory and open the file in the editor.

First Code Snippet For Testing

The first thing we need to do is add the following code to ContextMenu.js.

//ContextMenu.js

$(function () {
    alert("ContextMenu.js is loaded!");
});

JavaScript Comment

The first line is obviously just a JavaScript comment. Any line that begins with two slash characters in a JavaScript file is considered a comment.  Actually, any time two slashes are found on a line, the rest of the line is considered a comment and will be ignored.  I like to add the JS file name because then when you open the file in a text editor (as we often do when editing JavaScript) you can quickly see which file you are working with.

jQuery ready() Method

The next three lines make up the call to the jQuery method called ready() which is a helper function.  It looks very much like a JavaScript IIFE (Immediately Invoked Function Expression).  If you've never seen one, it is something to behold: it is quite odd syntax.  But, if you break it apart you can make sense of it.

Let's do that now to show you what I mean.  Here's the rewritten code:

//ContextMenu.js

$(Initialize);

function Initialize() {
    alert("ContextMenu.js is loaded!");
}

Now you can see that we have a named function called Intialize().  We also still have that odd first part that starts with a $(.   That is actually a jQuery shortened syntax which represents a method named $()

That method is the jQuery $.ready() method but we shorten it to $().  That method will run only after the entire HTML DOM (Document Object Model -- all HTML elements) are loaded.  This allows us to know when the page is completely loaded so we can then do things with the HTML elements if we need to.

In our case, we want :

  1. the page to load - we are notified of this in the $() method. 
  2. our intialization code to run

I've broken the Initialize function out into its own named section to clear this up, but as you can tell in the original code listing, I don't have to do that.

$() Method Takes One Parameter

The $() method takes one parameter.  The parameter can be one of two things:

  1. a function name -  this is what we used in our second example
  2. an anonymous function - this is what is used in our first example

An anonymous function does not include a name and has the following form:

function () { 

// function body

} 

Our original anonymous function is :

function () {
        alert("ContextMenu.js is loaded!");
    }

When that function runs, it will simply show up popup dialog.  To get it to run when the page loads, we add it to the $() method.

To do that we simply wrap that anonymous function with the $() method call.

Take a look at it again and now it'll probably all make sense.

$(
    function () {
        alert("ContextMenu.js is loaded!");
    }
);

Here's How It Works

When the page loads, the jQuery method $() will automatically be called.  When the $() method is called it will run the anonymous method which contains the one line to show a popup dialog (alert).

Now that we have the code we just need to add a reference to the script where we want to use it.

Where Do We Add the Script Reference?

The work we will complete in Part 2 of this article will work with the Home/Index.cshtml file.

Since that is the fie we will be working with, you may think we just need to add a <script> tag in that file and everything will be hooked up.  

Learn & Understand Everything You Can

Let's try that and just see what happens to clear this all up. It will also lead us to understand JavaScript file loading a bit better.  Knowing all of these pedantic little things are what make you a great web developer.

Open up your Index.cshtml file and add the following line of HTML at the bottom:

<script src="~/Scripts/ContextMenu.js"></script>

What About the Tilde (~)?

First of all, the tilde character is simply a way to tell an ASP.NET MVC to start searching for the file by going to the Application root and then following the path.

Go ahead and run your app again. 

When you do, you will expect the alert dialog to appear, but it will not.

Keep the web page up and now let's take a look at the source in the browser.

Most browsers allow you to do this by right-clicking anywhere on the page and selecting View Page Source... from the context menu.  I'm using Chrome.

view page source

Once you choose that you'll see the actual HTML that our C# MVC Web application creates and sends to the browser.

index.cshtml browser source

Take a close look at line 36 in that listing and you will see that our ContextMenu.js is loaded at that point.

The subtle reason that our code doesn't fire is related to where the jQuery library is actually loaded.  Do you see it further down on line 43?

Attempted To Use Library Methods Before They Load

That means we have attempted to access jQuery methods ( the $() method ) before we ever loaded the entire jQuery library.   This is further proven if you open your web browser's console window which displays errors.  Note: This works in Chrome and probably works in other browsers, but I only tested in Chrome due to how much time I'm spending on this article. 

In Chrome and many other browsers you can press the F12 key to open the console window.  When I do that, I see the following:

console window error

The error tells us that $ is not defined.  That is a very good clue since it is the jQuery variable that is not defined.  It even tells us that the error occured on line 3 of the ContextMenu.js which is very helpful.  If you click that in Chrome it takes you to the line of code in the ContextMenu.js which is our line which contains $(.

How Do We Fix This?

It is very easy to fix this since we know all about _Layout.cshtml.  That file loads all the content that we really have so far and it is the one that is responsible for loading the jQuery library.  Take a look at _Layout.cshtml again and go to the bottom and you will see the reference to the jQuery library near the bottom.

Let's delete the <script> line from our Index.cshtml and move it to the _Layout.cshtml, after the jQuery <script> tag.  The _Layout.cshtml file will now look like the following: (I've highlighted the line we added.)

moving script to layout.cshtml

Once you make that change.  Build and run again and you'll see the alert dialog appear when the page loads.

Here's something additionally interesting. Notice that the Load event completes before the browser even renders the page.  Since that is true the page hasn't even rendered yet, in the background and looks as if there is no content.  Once you click the OK button on the alert dialog you will see the content render in the browser.

alert dialog

There's just one more small thing to show you so you can understand where the CSS Styles are coming from.

Where Do CSS Styles Come From In ASP.NET MVC?

There isn't much to this ASP.NET Web application yet, but somewhere along the line we did get some slight styling that again almost feels like magic.  The slight style shows up at the top of the application where the web page says, "Application Name".  It looks somewhat like a Navigation bar and when you float over the "Application Name" text the text changes color from a smoke grey to a brilliant white.

navbar example

Again, that navbar is defined in our _Layout.cshtml file.  That means it will appear at the top of every View we add to the application.  

The HTML source for the NavBar is an HTML <div> tag located just inside our <body> content.

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
            </ul>
        </div>
    </div>
</div>

As you can see there is a CSS class set on the div that is : navbar navbar-inverse navbar-fixed-top

Those styles are defined in Bootstrap.css and that file is linked in at the top of _Layout.cshtml.

CSS Styles and the Content Folder

There are also a few CSS styles created by Visual Studio template which are stored in the Site.css file.  All of these files can be seen in the Content folder in the Solution Explorer.  The Site.css is the location where we will be adding our custom styles to create our ContextMenu UI in Part 2 of this article series.

Content CSS folder

One More Razor View Engine Command

Let's take a look at one more Razor Engine View command since it is right here.  You probably saw the following line of code in the previous listing:

@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

Hopefully you are now trained so that any time you see a @ symbol in a .CSHTML file you instantly think, "Hey, Razor is doing something here and this is C# code."

That is an Html Helper object (@Html) and it is calling a method named ActionLink().  The ActionLink method takes a five parameters and may have some other overloads.  The first parameter is the link text that the user will see.  The second parameter is the Controller that will handle the link and the third parameter is the Action inside the Controller that will be called.  So, clicking that link will call our Index.cshtml page.  It's the ASP.NET MVC equivalent of the home page. 

Foundation Is Set: Now You're Ready

Our understanding and structure is now in place and with the knowledge you have gained from this article you are ready to build a real working ASP.NET MVC Application.  

If you've followed along you have a much stronger understanding of the structure and workings of an ASP.NET MVC application and it will serve you well in your ongoing web development.  Thanks for reading my article.  

Code Download

The code download is just the simple project as we have created it so far and includes the new JavaScript file (ContextMenu.js).  The first time you build the application will retrieve the MVC assemblies via the Nuget Package Manager.  

History

03/22/2017 - first release of Part 1 - basic template project included.

License

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

Share

About the Author

raddevus
Software Developer (Senior) RADDev Publishing
United States United States
The CP editors went to Canada and all I got was this crummy sig line.
My web site, blog and other dev projects including C'YaPass : http://raddev.us^

You may also be interested in...

Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
Daniel Wilianto28-Mar-17 18:10
memberDaniel Wilianto28-Mar-17 18:10 
GeneralRe: My vote of 5 Pin
raddevus29-Mar-17 3:06
mvpraddevus29-Mar-17 3:06 
QuestionVery Very Nice Pin
Member 1306769925-Mar-17 11:46
memberMember 1306769925-Mar-17 11:46 
AnswerRe: Very Very Nice Pin
raddevus25-Mar-17 12:44
mvpraddevus25-Mar-17 12:44 
QuestionCreate Desktop UX With ASP.NET MVC Part 1 Pin
Member 1086218024-Mar-17 4:49
memberMember 1086218024-Mar-17 4:49 
AnswerRe: Create Desktop UX With ASP.NET MVC Part 1 Pin
raddevus24-Mar-17 5:55
mvpraddevus24-Mar-17 5:55 
GeneralRe: Create Desktop UX With ASP.NET MVC Part 1 Pin
Member 1086218024-Mar-17 10:28
memberMember 1086218024-Mar-17 10:28 
GeneralMy vote of 5 Pin
DerrickCraps23-Mar-17 1:14
memberDerrickCraps23-Mar-17 1:14 
PraisePerfect introduction for a beginner! Pin
DerrickCraps23-Mar-17 2:25
memberDerrickCraps23-Mar-17 2:25 
GeneralRe: Perfect introduction for a beginner! Pin
raddevus23-Mar-17 3:23
mvpraddevus23-Mar-17 3:23 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.181119.1 | Last Updated 22 Mar 2017
Article Copyright 2017 by raddevus
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid