Step-by-step ASP.NET MVC Tutorial for Beginners | Mosh

Programming with Mosh · Beginner ·🛠️ AI Tools & Apps ·10y ago

Key Takeaways

The video provides a step-by-step ASP.NET MVC tutorial for beginners, covering topics such as MVC architecture, routing, controllers, actions, and views. It also covers the use of tools such as Visual Studio, Resharper, and Bootstrap.

Full Transcript

[Music] hi welcome to the complete AET MVC course my name is m shadani and I'm going to be your instructor over the next few hours before we get started let me quickly show you the application we're going to build this application is called vidly and it's supposed to be used at video rental stores we have two different roles here admin and staff member let me log in as admin on the top we have three links on the navigation bar new rental customers and movies let's start with the list of customers you can see this table has pagination sorting and searching if we delete the customer we get this bootstrap dialog box for confirmation we can also add a new customer and here we have a business rule if the customer wants to go on a monthly quarterly or annual membership type they have to be at least 18 years old otherwise we get a validation error so you see this application is more than just CR there are some business rules involved now let's take a look at the list of movies it's very similar to the list of C customers but let me show you something if I log out and log in as a guest or a staff member and by the way we can log in with Facebook as well so with what you learn in this course we can easily extend this application and add support for Google and Twitter authentication let's log in now back in the list of movies I get a readon view of the list of movies I cannot add update or delete a movie so this video features are only available to admins now with the list of customers and movies in the database we can add a new rental so when a customer comes to the counter we look them up [Music] here and then we add all the movies they're going to rent and again here we have another business rule these movies have limited availability so as we renting out these movies we need to keep track of availability of movies so once again this application is more than just crot so are you excited to build this application with me I hope you are let's [Music] begin so what is this MVC all about well MVC stands for model view controller and it's one of architectural patterns for implementing user interfaces although it was originally developed for desktop applications back in 1970s it's been widely adopted as an architecture for web applications and as a result many Frameworks have been created that enforce this pattern as. MVC is one of them there are many other similar NVC Frameworks like Ruby un rails or Express for note in an NVC application model represents the application data and behavior in terms of its problem domain and independent of the user interface for example in our video rental application our model will consist of classes like movie customer rental transaction and so on these classes have properties and methods that purely represent the application State and rules they're not tied to the user interface which means you can take these classes and use them in a different kind of app like a desktop or a mobile app they are plain old CLR objects or pocos V in MVC represents the view and it's the HTML markup that we display to the user and C is a controller which is responsible for handling an HTTP request for example imagine our application is hosted at VD lin.com when we send a request to bitly.com movies a controller will be selected to handle this request this controller will get all the movies from the database put them in a view and return the view to the client or the browser so with this architecture you see each component has a distinct responsibility and this results in better separation of concerns and a more maintainable application now there is one more piece to this architecture which is not in the acronym MVC but is nearly always there it's a router earlier I told you that when a request comes in the application a controller will be selected for handling that request selecting the right controller is the responsibility of a router a router based on some rules knows that the request with the URL slm mov should be handled by class called movies controller more accurately it should be handled by one of the methods of this class because a class can have many different methods in as MVC we refer to methods of a controller as actions so it's more accurate to say that an action in a controller is responsible for handling a request so this was as NVC in 3 minutes okay to follow along with this course first of all you need visual studio 2013 or higher in this course I'm using visual studio 2013 Community Edition which is free also I'm going to use a few plugins to increase my productivity and make my development experience more enjoyable so open up visual studio under Tools go to extensions and updates on the left side select online and here search for visual studio productivity power tools so you can see I have installed productivity power tools 2013 this is an extension that brings in a lot of useful features to increase your productivity next search for web Essentials again you can see I've installed this plugin in your case you'll see a button to install this plugin and the last plugin which is optional is resharper so you don't necessarily need resharper to follow along with this course but I highly recommend you to download and install it because I'm going to show you lots of time saving tips and tricks re sharper is a commercial plugin and the price is somewhere about $7 to $90 a year and I highly recommend you to invest this money and add resharper to your toolbox because the number of hours you will save per year will save you far more than $90 a year and by the way I'm not a resharper affiliate I don't get a penny from promoting this I'm just recommending resharper because I only teach you the best tools because I want you to be outstanding in your career now whether you want to get a resharp a license or not is your decision but you can get a free 30-day trial version of resharper to try the time saving tricks I'm going to show you in the course and if you don't want to get resharper that's perfectly fine don't panic I will show you how to get things done without resharp as well all right our development environment is ready next we're going to create our first MVC application so in Visual Studio go to the file menu new project on the left side under templates expand visual C and web and here select as.net web application I'm going to call this vidly and store it in my C drive in the projects folder now here you see add to Source control is selected because I'm going to add this to git if you don't have git on your machine or you don't want to add this on Source control don't worry about this so untick the checkbox okay now here in the list of templates select MVC and make sure host in the cloud is not selected because we're not going to deploy this in the cloud yet select okay now because I selected add to Source control I see this dialog box where I can select either team Foundation Version Control or TFS or git I'm going to select git okay okay beautiful our project is created let's see what we've got inside this project so open up solution Explorer here we've got a bunch of folders like app underline data which is where our database file will be stored we have app underline start which includes a few classes that are called when the application is started let's take a look at one of these for example route config so this is the configuration of our routing rules here you see we have a route with the name default and with this URL pattern so if a URL matches this pattern the first part of the URL is assumed to be the name of the controller the second part is assumed to be the name of the action and the third part is an ID we can pass to that action with this rule if you send a request to slm moviespopular as. the runtime will call a method or an action called popular in movies controller or as another example if you send a request to slov sledit SL1 as at the runtime will call the edit action of the movies controller and will pass one as the ID to this action so back here you can see we have some default values in this route so if our URL doesn't have any of these parts it will be passed to the home controller similarly if the URL has only the controller but not the action it will be handled by the index action so if we go to slm movies since the action name is not specified in the URL it will be index in movies controller also you can can see that ID is an optional parameter because not every action needs an ID we only need this when we working with a specific resource like a movie or a customer with a given ID we also have this content folder where we store our CSS files images and any other client side assets next we have controllers and you can see our default project template has three controllers account which has actions for sign up login log out home which represents the homepage and manage which provides a number of actions for handling requests around user's profile like changing password enabling two Factor authentication using social logins and so on we have fonts which shouldn't really be here in the route I would personally prefer to move this under content folder but we'll leave that for a later lecture we have models so all our domain classes will be here next we have scripts where we store our JavaScript files and finally we have views so V in MVC now look here we have folders named after controllers in our application let me expand controllers again so we have account home and manage controller and interestingly we have three folders with the same names excluding controller so by convention when we use a view in a controller as.net will look for that view in a folder with the same name as the controller we also have a folder called shared which includes the views that can be used across different controllers and finally we've got a few other files here fave icon is the icon of the application displayed in the browser Global asax is one of the traditional files that has been in asp.net for a long time and it's a class that provides hooks for various events in the application's life cycle so let's expand this and open the C file so when the application is started this method will be called and here you can see we are registering a few things like the routes so when the application started we tell the runtime these are the routes for our application next we have packages. config which is used by newg get package pack manager if you have never worked with new get it's a package manager similar to npm or note package manager or Bower if you have never worked with any package managers before we use them to manage the dependencies of our application so let's say our application has dependency to five external libraries instead of going to five different websites for downloading these libraries we use a package manager and this package manager will download these dependencies from its Central Repository also if in the future one of these libraries has a newer version again we use our package manager to upgrade one or more of the existing packages we don't have to go to five different websites we also have this startup.cs which is a new approach Microsoft is taking for starting the application so in the next version of as.net called as.net core 1.0 which is not ready yet they've dropped global. asax and all the startup logic is implement mented in this startup class and finally we have web.config which is an XML that includes the configuration for application out of all the elements you see in this XML mostly you will need to work with only two sections connection strings which is where we specify database connection strings and app settings which is where we define configuration settings for our application okay now that you have a good understanding of what is inside this project let's see the building blocks of MVC architecture in action okay and solution Explorer right click models and add a new class here I'm going to call this movie we give it a couple of properties like integer ID and string name to quickly create a property just type prop press tab this is a code Snead you specify the type then press tab again and the name of the property so this class is a plain old CLR object or Poco which represents the state and behavior of our application in terms of its problem domain in this case it doesn't have any Behavior or logic it just has a couple of properties which we use for representing State now let's say we want to create a page where we randomly pick a movie and render its details assuming that this page would be under slm movies SL random we need to create a controller called movies controller with an action called random so in solution Explorer right click controllers add controller here we have different templates and most of them are used for autogenerating some code which we call scaffolding but we are not going to use any of these templates because I want you to learn how to create a controller from scratch so select the first one add call this movies controller so this controller is a very simple class that derives from the controller class and and here we have an action called index which returns action result I'm going to change the name of this action to random so this will be called when we go to SL movies SL random now in this method I'm going to create an instance of our movie model so movie new movie now because I'm using resharper resharper automatically resolve the name space for this class if you're not using resharper you need to go on top of this file and manually type using vitle models back here let's set the name of the movie Shrek in a real world application we often get a model from a database but for now to keep things simple let's just focus on the core building blocks of MVC apps now here you can see that this method is returning a view and the reason this view is Red is because resharper is telling me that this view file does not exist in the application so in the solution Explorer under views look inside movies folder we don't have a view called random so right click add view call this random here we have template which we can use to autogenerate a view but we're not going to to use this feature under options you can take this box to create this view as a partial view a partial view is not a complete page it's like a widget that we can reuse on different views we are not interested in that so ontick here we have a checkbox for selecting the layout for this view a layout is like a template or a master page we want all the views in our application to have the same look and feel so let's select the layout by default our NVC project has a layout under views shared called underline layout so select this and add the view okay here you see a mixture of HTML and C code prefixed with an add sign so on the top we have a block and inside this block we are setting two properties one is viewb back. title which we'll look at later but basically this is going to be the title of our page shown in the browser and next we're setting the layout for this view after this code block we have just plain HTML now I want to go back to the controller press control and tab this way we can switch between open tabs look view is no longer red because now we have a view on the dis now I want to put this model movie model in our view so we can render it again control tab to go back to the view I want to change this heading and render the name of our movie so we need to write C code we start with ADD sign and then type model every view has this property which gives us access to the model we passed to it in the controller now in the Intel sense note that the type of this model is dynamic it's not a movie so if I use the dot op operator I cannot see the name property of this movie here so on top of the file we need to use a directive to specify the type of the model for this view so add sign model and this has to be lowercase and here we specify the fully qualified name of our model class so the name of the application vidly models. movie now if you're using resharper you don't have to remember this fully qualified name you can just type movie and press enter resharper automatically resolves the namespace okay back here now we can type model Dot and look we've got ID and name properties here so let's render the name all right now let's run the application because we are in the random View and this view is inside the movies folder if you press control and F5 now our browser will take us to SL movies SL random so contrl F5 okay congratulations so you have seen a Model A View and a controller in action throughout the rest of the course we'll work on more sophisticated scenarios but the fundamentals will be very similar to what you have seen in this video okay now let's go to the homepage I don't like this default template that comes with our application it looks a little bit ugly so let's find a better template our as.net mvcc application uses bootstrap as its front end CSS framework so to replace this template we need to find a bootstrap template head over to boot swatch.com here you see a bunch of different templates for bootstrap under themes select Lumen so scroll down our navigation bar will look like this here we can see the buttons tables forms so nice and clean now under Lumen select bootstrap.css this is the bootstrap CSS file but with modified Styles you need to save this file on the disk and I would suggest to call it bootstrap D Lumen to distinguish from the original bootstrap file then added in the project under the content folder so here you see I have both bootstrap and bootstrap D Lumen now we need to replace the reference to bootstrap with bootstrap Lumen so under app underline start open up bundle config this is where we define various bundles of client side assets for example we can combine and compress multiple JavaScript or css files in into a bundle and this way we reduce the number of HTTP requests required to get these assets when a page is loaded and this results in a faster page load so here you see we have a few bundles one for jQuery and inside this bundle we have the jqu script we have another bundle for jqu validation plugin and inside this bundle we have all the files that match this pattern we have another bundle for modernizer one for boot St and another one for our CSS assets inside our CSS bundle we have bootstrap and site. CSS which includes a few generic styles for our application now add Dash Loom and here now because we have modified our C code we need to compile it in order to see the changes so press control and F5 to compile and run the application again all right here's our new homepage with a new look and fi now get ready for a quick quiz I want to test your knowledge about what you have learned in this section so this was just a quick introduction to as.net MVC now let me quickly give you a heads up about what is coming up over the next few sections in the next section we're going to look at the fundamentals of as.net MVC in detail by the end of this section you will have a good and in-depth understanding of how h.n MVC works next we'll use Entity framework to connect our application to a database we'll be using Code first workflow for this so if you're new to code first this is a great eye opener then we'll add forms and Implement validation so at this point you will know how to implement Crow operations in asp.net MVC next we'll look at using as.net web API to build restful services so I will explain what restful convention means and how you can create restful services using aset web API once we build our apis we'll shift our Focus to client side development so we'll use jQuery to consume some of these apis in this section you're going to learn about two very useful jQuery plugins next we'll Implement authentication and authorization using h.net identity framework so you will understand exactly how h.net identity works and how you can customize it for your applications next I'll talk about performance optimization I will introduce you to three tier architecture and for each tier I will show you how you can optimize the performance of your application in that tier then in section 10 we'll put everything together and I will show you a systematic way to build a feature end to end and finally in the last section you'll learn about building and deployment so there's a lot to cover and I will see you in the next [Music] section well hello it's MOS here your instructor I just wanted to let you know that what you have been watching so far is actually picked from my complete aset MVC 5 course on Udi in case you're interested to have the complete course you can get it with a discount using the link in the video description and if not that's perfectly fine continue watching as the next section is coming up have a great day [Music] in this section we're going to take a closer look at building blocks of as.net MVC and by the end of this section you will have a much deeper understanding of how this framework Works more specifically we're going to look at controllers actions routing views and view models so let's get started so in the last section you noticed that our random action returns action result this action result is the base class for all action results in as.net MVC so depending on what an action does it will return an instance of one of the classes that derive from action result in a random action we're calling this view method here which is just a helper method inherited from the base controller class this method allows us to quickly create a view result alternatively we can return a view result like this return New View result you can see that it's easier to just call the view method and this approach is way more common amongst asp.net MVC developers now you might be asking why is the return type of this method action result even though we're actually returning a view result well in case of this action we could simply set the return type to view result and this is actually a good practice especially when it comes to unit testing this action this way we'll save ourselves from an extra cast in our unit tests we'll look at unit testing in the second part of this course but sometimes it's possible that in an action we may have different execution paths and return different action results in that case we need to set the return type of that action to action result so we can return any of its subtypes okay view result is one of the action results that you work with most of the time let's take take a look at other types of action results we have partial view result to return a partial view content result to return Simple Text redirect result to redirect the user to a URL redirect to Route result to redirect to an action instead of a URL Json result to return a serialized Json object file result to return a file HTTP not found result to return a not found or 404 error an empty result which is used when an action doesn't need to return any values like void as you can see for all these types except emper result we have a helper method in the base controller class so let's see some of these in action back in the code I'm going to comment this out let's return content like hello world let's run the application with control and F5 and navigate to slov random so look we just get plain string content in the response another example let's return HTTP not found now build the application with control shift B this will compile the application without opening a new tab in the browser now press press alt and tab to switch back to Chrome and contrl R to refresh the page okay look we got this standard 404 error now for enter result we don't have a helper method so if you want to create an action that doesn't return anything you need to return an instance of empty result like this return new empty result control shift B to build alt and tab control R okay look there's nothing in the response and the last example return redirect to action here we specify the name of the action and then the controller now sometimes as we are redirecting the user from one page to another we need to pass arguments to the Target action to pass arguments we use an anonymous object as the third argument to this method so new Anonymous object let's say page is one and sort by is name build back to Chrome refresh okay look we got redirected to the homepage and you can see see in the browser address bar that the arguments we sent are appearing as part of the query string so this is pretty much all you need to know about action results by the way don't think you need to memorize any of this stuff for the most part you'll be using view HTTP not found and redirect result in the last lecture we looked at action results which are the output of our actions now let's take a look at action parameters which are the inputs to our actions when the request comes in the application asp.net MVC automatically Maps request data to parameter values for Action methods so if an action method takes a parameter the NVC framework looks for a parameter with the same name in the request data if a parameter with that name exists the framework will automatically pass the value of that parameter to the Target action this parameter value can be embedded in the URL it can be in the query string or in the data posted using a form so back in the movies controller I'm going to create a new action public action result edit with a parameter called ID and here I just want to return simple content ID equals plus ID let's run the application first we compile with with control shift B alt and tab back to the browser I'm going to change the url to movies sledit SL1 this is an example of a parameter embedded in the URL you can see that it gets automatically mapped by the MVC framework I can also pass this parameter in the query string so contrl L I'm going to change this to ID equal 1 it gets mapped again name but let's see what happens if I rename this parameter to movie ID to rename we press f2 so all references are renamed automatically movie ID one more time build back to the browser refresh we got an exception the parameters dictionary contains a entry for parameter movie ID so if not NVC couldn't find a parameter called movie ID embedded in the URL or in the query string or in the request body passed by form and that's why we get this exception now I can change the query string parameter to movie ID there is gone but in this case I cannot embed one in the URL because the name of the parameter in our default route is ID it's not movie ID let's have a look at our default route one more time so in solution Explorer open up Route config look here's our default route and the parameter we have here is called ID so the value that we pass here will be identified as ID not movie ID and in movies controller this movie ID will not be initialized when this action is called now let's rename this back to ID so this is how a that NVC Maps request data to parameters of our actions we can also use optional parameters in our actions so let's create a new action public action result index so this action will be called when we navigate to movies now in this action imagine will return a view with the list of movies in the database we can add two optional parameters here page index and string sort by so if page index is not specified we display the movies in page one and similarly if sort by is not specified we sort the movies by their name now to make a parameter optional we should make it nullable so for page index I'm going to add a question mark here to make it a nullable integer and for sort by we don't have to do anything because the string type in C is a reference type and it's nullable now now inside the action we check to see if these parameters have a value so if page index has value I put the not operator here so if it doesn't have a value I initialize it to one similarly if string is null or wh space we pass sort by here then we initialize it to name and finally for the purpose of our demo I'm just going to return simple content so string. format page index equals the first parameter and sort by equals the second parameter and I pass page index and sort by here okay now build control shift B back to the browser let's go to movies so you can see I didn't have to specify any parameters and by default page index is one and sort by is name I can overwrite this parameter so I can pass page index set it to two and you can see it's updated here but sort by is still name I can overwrite that too sort by release date now it's updated now in this case we cannot embed these parameters in the URL because that would require a custom route that includes two parameters in the next lecture I will show you how to create a custom route so this default route in our application works for most scenarios but there are situations where we need a route with multiple parameters for example in our video rental app we may want to have a route like this where we can get the movies by the release year and month so let me show you how to create a custom route in route config class before our default route we call route. map route the reason you need to add this route before the default route is because the order of these routes matters you need to Define them from the most specific to most generic otherwise a more generic route will be applied to a URL and that's not what you want this method has a few overloads the one we use most of the time is the one that takes three parameters name URL and default so let's give our new route a name and this name should be unique so movies by release date now let's put this on a new line to keep the code consistent and clean next parameter is the URL pattern so so movies SL relased here we need two parameters year and month I note that I've enclosed these parameters in curly braces now the third argument we need to specify the defaults we use an anonymous object for that so new anonymus object here we set the name of the controller to movies and the action to buy release date that's it that's how we Define a custom route now let's create this action so save back to movies controller I show you a quick way to create an action type MVC action 4 and press tab so this is another code snippet so I we call this by release date this action takes two parameters year and month for the month we could use a bite because the largest number we want here is 12 but it doesn't really matter now here again I want to return simple content so year plus slash plus month now build back to the browser let's navigate to movies slash relased I'm not specifying any parameters we got a 404 error because our URL has not matched any of our route patterns now let's put the year and the month so our route parameters are here we can also add constraints to our route for example let's say we want to enforce that the year and month parameters to be four and two digits respectively so back in our route definition we Supply another argument to map route method again we use an anonymous object and here we can use regular Expressions to apply constraints so I want the year to be four digigit number so set it to a Verbatim string back SL d which represents a digit and the number in curly braces represents the number of repetitions the reason I put an ad sign here is because backslash is an escape character and if you don't use AD Sign Here we would have to add another backslash and this looks a little bit ugly so undo that's better now similarly I'm going to set month to a regular expression back SL D with two digits build back to the browser now if I refresh we got a 404 error and that's because of our constraint but if you add a zero here everything works now let me show you another example let's say we want to constraint the year to 2015 and 2016 now this doesn't quite make sense in the context of listing movies by year but sometimes you may want to limit the route parameters to a few specific values again we can use a regular expression to apply that constraint so I'm going to change this to 2015 or 2016 so this is how we Define custom routes in as notet MVC in the next lecture I will show you a cleaner way to create a custom route okay look at this code currently we have only one custom route here but if you're working on a large application sooner or later this file is going to grow with a lot of custom routes and over time it becomes a mess plus another issue with this approach is that you have to go back and forth between your actions and custom routes and the third issue is that if we go back to movies controller and rename this action to by release here you can see it's not updated here and that's because of this magic string so when we rename a controller or an action we have to remember to come back here and apply that name change as well so this code is fragile because of this magic strings in as MVC 5 Microsoft introduced a cleaner and better way to create a custom route instead of creating the route here we can apply it using an attribute to the corresponding action so you might ask M why did you teach me the old and poor way of creating custom routes because you may be working with an existing codebase with convention based custom routes so you need to understand how they work but if you're building a new application or improving an existing one I would recommend you to use attribute routing now let me show you how to define this custom route using an attribute first in order to use attribute routing you need to enable it so routes. map MVC attribute routes we call this method now let's delete this route save back to the controller we apply the route attribute and here we pass the URL template so movies slash relased slash year slash Monon now to apply a constraint we add colon and then we add reject to apply a regular expression this is like a function that we call in parenthesis we pass the actual regular expression so digit repeated four times note that this regular expression is not a string so unlike verbatim strings we have to repeat this backslash twice now with attribute routes we can also apply other kinds of constraints for example I can apply a second constraint to this month parameter so after Rex colon again this time I'm going to use range to set a range between 1 and 12 so you see attribute routes are more powerful we also have a bunch of other constraints like min max Min length and max length for Strings energer float GID and so on you don't have to memorize any of these constraints just be aware that they're supported by the framework if you need to apply constraints to your attribute routes just Google as.net MVC attribute route constraints okay so far we have looked at controllers and routing in detail now we're going to slowly transition to views so in the next lecture I will show you a few different ways to pass data to views earlier in the introduction section we created this action to display a movie in this action we passed our model to the view by passing it as an argument to the view method there are two other ways to pass data to views and that's what I'm going to show you in this lecture one way is to use the view data dictionary so every controller has a property called view data which is of type view data dictionary so in this example we can pass our movie to the view like this and we remove it from here now let's go to The View with resharper we can quickly navigate to The View for this action by putting the cursor on The View method and pressing contrl B and this drop down you see the name of the view random. CSH HTML if you're not using resharper you need to go to solution Explorer and find The View under views movies right here okay now instead of using model property we need to use view data now dot look we can't access the name property of our movie because each item in the dictionary is of type object so we need to explicitly cast it to the movie now don't type anything just watch for a second because this this code is going to get a little bit ugly that's what I meant so all these noisy parenthesis compare this to what we had before model. name which one do you think is better it's obvious another problem with this approach is this magic string here so back in the controller if we change this movie to random movie we have to remember to go back in the view and make this change here as well otherwise we'll get a non reference exception so this way of passing data to the Views is fragile we had this in the very first version of NVC and then Microsoft decided to improve this but in a very poor way so they introduced viewb which is a dynamic type so back in the controller instead of using view data with a magic string we use view bag with a magic property so this movie property is added to the viewbag at runtime which means we don't get compile time safety if we decide to change this magic property to random movie again we have to remember to go back in View and change it here plus we'll have the casting issue as well so honestly I have no idea of what Microsoft was thinking when they introduced this view bag as an improvement for view data so please do not use view data or view back if you want to pass data to a view just use the approach I showed you earlier so back in the controller we get rid of these and just pass the movie Object here now you might be curious where does this movie Object go in the view result let me show you so I create an instance of view result view result view dat. model so this movie Object we pass here will be assigned to this property this view method here would take care of that so we don't have to write all this extra code what I want you to note here is that this view data it's not a regular dictionary it's a view data dictionary so you can either use it as a dictionary with key value pairs or use its model property to work with an object and that's the preferred way next we're going to look at view models in our random view currently we just displayed the name of a movie but what if we also wanted to display the list of customers who have rented this movie in our domain model there may not be a relationship between the movie and customer classes so we need to pass two different models to this view one is the movie The Other is the list of customers but here we have only one model property so how do we solve this problem we use a view Model A View model is a model specifically built for a view it includes any data and rules specific to that view so let's see a view model in action first I'm going to add a customer class to the models folder add class customer let's give it a couple of properties ID and name now we use this models folder purely for our domain classes like movie customer and so on we put view models in a separate folder so let's create a new folder add new folder view models and then we add a new class here random movie view model so as a convention we use the view model suffix this class needs two properties one is the movie note that as I type the movie Here resharper automatically added this name space here the other property is is a list of customers now let's go back to our controller and the random action I'm going to quickly create a list of customers we use the object initialization syntax to add two customer objects here customer one and two now we create a view model object random movie view model again resharper automatically resolve the namespace now let's initialize the movie property and the customers okay so this is our view model now instead of sending the movie here we send the view model now look we have a red underline here argument type random movie view model is not assignable to model type movie so basically that means in the random view because the type of the model for this view is the movie we cannot give it a view model so we need to change this to random movie view model now we have an error here because our view model doesn't have the name properties so we change it to model. movie. and you can see here we have access to model. customers in the next lecture I will show you how to render the list of customers okay in this lecture we're going to examine the razor view syntax in as.net MVC so you have learned that here we can write C code by prefixing it with an AD Sign to render the list of customers we can simply use a for each block so add sign for each of our customer and model. customers we use a code block here this is compulsory in as.net MVC views even if what you're going to put inside the for each block is only one line now here inside this block we we can either continue writing C code like using an if statement or we can write HTML so the view engine in MVC called razor view engine knows how to parse this syntax let's say we want to display these customers using list items so outside this for each block I use the UL tag let's close it here and inside the forage block we use Li and here we switch back to C so AD Sign customer. name we can also use an if block to conditionally render content for example if no one has rented this movie before we want to display a custom message so if model. customers. count is zero code block here we can add a paragraph no one has rented this movie before or if you don't want to use the P tag you can simply use text this is not part of the standard HTML but it's something that the razor view engine understands so if no one has rented this movie this if block will render our text without any markup around it okay now we add an else block here and move this UL right here so you can see working with razor views is pretty easy now let me show you a few more techniques let's say here in H2 you want to conditionally add a class popular if the movie has been rented by at least five customers otherwise we don't want to have this class here how do we do that first we use a code block so add sign code block here we can write any c code so I'm going to going to declare a variable call it class name and initialize it like this if model. customers that count is greater than five it should be popular otherwise it should be null now here we can render class name with this code if class name is null this class attribute will not be rendered in the final HTML it will be added only if class name is popular so let's try it run the application with contrl F5 okay right click the heading inspect look we don't have the class attribute because currently we have only two customers now let's go back to the view I'm going to change this condition to Greater Than Zero Save now we don't have to rec compile the application because this is just a view so we can switch back to the browser refresh now look at the heading we have the class popular so this is how you render classes dynamically by the way this technique is not limited to classes you can use this technique to render any attributes dynamically and one last tip you can add comments in your razor views using this syntax at sign star star at sign and we can make it multiple lines this is a comment on multiple light so earlier when we created a view I briefly explained what a partial view is in this video we're going to take a closer look at partial views so in solution Explorer open up views shared layout this is the bootstrap template that defines the overall look and feel of our website so we've got the standard HTML head and body sections inside the body we've got a div that represents our navigation bar let's collapse this hold down control and press M twice below this nav bar we have a container for our Pages note this call to render body method so so what we put in our views will be placed here when the view is rendered and you can see below that we've got a horizontal line and a footer now I told you that a partial view is like a small view that we can reuse on different views but partial views are not necessarily for reusing markup sometimes we can use them to break down a large view into smaller more maintainable partial views for example let me expand this navigation bar element again you can see that we have a fair amount of markup on this view while this is not terribly bad we can improve the maintainability of this layout by extracting the part that represents the navigation bar into a partial view so let's do that back in solution explore right click shared add view by convention we prefix partial view names with an underscore so let's call this underscore nav bar we need to tick this checkbox here create as a partial view this way this view will not have a layout okay now control tab to get back to the layout scroll up a little bit so here's our Navar element again put the cursor on this element hold down the control and press M twice okay collapsed contrl X cut back to navigation bar paste it here now we can see in this partial view we only have the navigation bar nothing else so next time we want to change something on our navigation bar we can simply jump to this partial view we don't have to scroll up and down in the main layout save now back to the layout so here's the content area of our Pages the navigation bar was above that so here we need to render that partial View weuse add sign HTML this is a property of our views which is of type HTML helper so it's a class that provides a number of useful methods to work with HTML we're going to use the partial method here we pass the name of our partial view underline navbar that's it that's how we use a partial view on another view now optionally we can pass a model to this partial view as the second argument of this partial method now in this case we don't have a model in our layout but let me temporarily just declare a model for demonstration so on top of this view I'm going to add the model directive and let's set this to random movie view model now here if I don't specify a model the model that is currently passed to this layout view will be automatically passed to this partial view but let's say this navbar expects a movie not the entire random movie view model then we can supply a model as a second argument so model. movie okay we've covered a lot of ground about various components of asut MVC so in the next lecture you will get a cheat sheet to quickly overview the materials in this section and then I'm going to give you an exercise to put what you have learned in action okay I want you to use what you have learned in this section and Implement a few simple features in our vidly app so you can see here on the navigation bar I have changed application name to vidly and now we have only two links customers and movies in the customers page we have a table with the list of customers and currently we have only two customers now these customers are not coming from a database I've just hardcoded them in my action for this exercise don't worry about the database in the next section we're going to use enti framework to generate a database for our application now back here in the list of customers if I click on John Smith I go to a new page at this address customers SL details SL1 which is the ID of that customer if I change this to two you see Mary Williams but if I change this to three we get a standard 404 error page because we don't have have a customer with that ID now in the future we can replace this boring standard page with a custom design but for now don't worry about it what I want you to do as part of this exercise is to cater for various situations like when we have a customer versus when we don't have a customer now let's go back in the list of customers if we don't have a customer we should see a message like we don't currently have any customers so let me temporarily go back to my action and comment out the code that generates this list and then refresh the page look this is what I was talking about so when implementing this view cater for these scenarios the list of movies is very similar currently we have two hardcoded movies Shrek and Wall-E and there's no link under these movies if you want you can add them but it's going to be exactly like the exercise for customers so go ahead and use what you have learned in this section to make these changes and by the way before you get started look at the PDF I've attached to this lecture there are additional materials in that PDF that you need to read in order to do this exercise now if you want to see my solution we can simply head over to github.com dhamani here you see I have a repository created for this course vitle d mc-5 here we can get the latest source code or one of the previous versions of the application you can see currently I have eight commits so let's take a look so as I'm recording these lectures and modifying this application I make small changes to the code and commited to the repository for example you can see in the previous lecture I extracted the navigation bar into a partial view let's take a look at this commit I'm going to change the view mode to to split because it's easier to see the before and after changes so we can see in layout. CSH HTML on the left side this is what we had and on the right side this is what we currently have so the red lines were removed and the green lines were added you can see that I removed this div which was our navigation bar and replaced it with html. paral method let's scroll down here is another file navbar CS HTML which is a new file because previously we had nothing here and now we've got all this markup for the navigation bar so you can see I've got another commit here solution section two exercise display the list of customers and movies so throughout this course as you do your exercises you can always come back here and look at my solution and by the way when required I always add comments to my solution so you know why I did something in a certain way so be sure to read these comments all right in this mo

Original Description

🔥Get the complete ASP.NET MVC course: http://bit.ly/2OBKf0w Want to learn ASP.NET MVC 5 from scratch in a fun, step-by-step and pragmatic way? Watch this tutorial and get started. Table of Content: 00:00 Introduction 02:48 ASP.NET MVC Architecture 05:31 Setting Up the Development Environment 07:38 Your First ASP.NET MVC 5 App 14:34 MVC in Action 21:18 Adding a Theme 26:49 Action Results 31:47 Action Parameters 37:42 Convention-based Routing 42:58 Attribute-based Routing 46:27 Passing Data to the Views 50:30 View Models 54:19 Razor Views 58:38 Partial Views I have several other courses on C#, Entity Framework, Angular 2 and more. Check out my courses here: http://programmingwithmosh.com/courses Stay in touch: https://www.facebook.com/programmingwithmosh/ https://twitter.com/moshhamedani
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Programming with Mosh · Programming with Mosh · 27 of 60

1 6 Visual Studio Tips to Increase Your Productivity | Mosh
6 Visual Studio Tips to Increase Your Productivity | Mosh
Programming with Mosh
2 Visual Studio Keyboard Shortcuts that Speed Up Debugging Applications | Mosh
Visual Studio Keyboard Shortcuts that Speed Up Debugging Applications | Mosh
Programming with Mosh
3 Backbone.js Tutorial Part 2 - Backbone.js Models: Working with Model Attributes
Backbone.js Tutorial Part 2 - Backbone.js Models: Working with Model Attributes
Programming with Mosh
4 Backbone.js Tutorial Part 3 - Backbone.js Models: Model Validation
Backbone.js Tutorial Part 3 - Backbone.js Models: Model Validation
Programming with Mosh
5 Backbone.js Tutorial Part 4 - Backbone.js Models: Model Inheritance
Backbone.js Tutorial Part 4 - Backbone.js Models: Model Inheritance
Programming with Mosh
6 Backbone.js Tutorial Part 1 - Backbone.js Models: Creating Models
Backbone.js Tutorial Part 1 - Backbone.js Models: Creating Models
Programming with Mosh
7 Backbone.js Tutorial Part 5 - Backbone.js Models: Syncing Models with the Server
Backbone.js Tutorial Part 5 - Backbone.js Models: Syncing Models with the Server
Programming with Mosh
8 Backbone.js Tutorial Part 6 - Backbone.js Collections: Creating Collections
Backbone.js Tutorial Part 6 - Backbone.js Collections: Creating Collections
Programming with Mosh
9 Backbone.js Tutorial Part 7 - Backbone.js Collections: Working with Collections
Backbone.js Tutorial Part 7 - Backbone.js Collections: Working with Collections
Programming with Mosh
10 Backbone.js Tutorial Part 8 - Backbone.js Collections: Fetching Collections from the Server
Backbone.js Tutorial Part 8 - Backbone.js Collections: Fetching Collections from the Server
Programming with Mosh
11 Backbone.js Tutorial Part 9 - Backbone.js Views: Creating Views
Backbone.js Tutorial Part 9 - Backbone.js Views: Creating Views
Programming with Mosh
12 Backbone.js Tutorial Part 10 - Backbone.js Views: Passing Data to Views
Backbone.js Tutorial Part 10 - Backbone.js Views: Passing Data to Views
Programming with Mosh
13 Backbone.js Tutorial Part 11 - Backbone.js Views: Handling the DOM Events
Backbone.js Tutorial Part 11 - Backbone.js Views: Handling the DOM Events
Programming with Mosh
14 Backbone.js Tutorial Part 12 - Backbone.js Views: Handling the Model Events
Backbone.js Tutorial Part 12 - Backbone.js Views: Handling the Model Events
Programming with Mosh
15 Backbone.js Tutorial Part 13 - Backbone.js Views: Handling Collection Events
Backbone.js Tutorial Part 13 - Backbone.js Views: Handling Collection Events
Programming with Mosh
16 Backbone.js Tutorial Part 14 - Backbone.js Views: Templating
Backbone.js Tutorial Part 14 - Backbone.js Views: Templating
Programming with Mosh
17 Clean Code: Learn to write clean, maintainable and robust code
Clean Code: Learn to write clean, maintainable and robust code
Programming with Mosh
18 C# Events and Delegates Made Simple | Mosh
C# Events and Delegates Made Simple | Mosh
Programming with Mosh
19 C# Generics Tutorial: Whats and Whys | Mosh
C# Generics Tutorial: Whats and Whys | Mosh
Programming with Mosh
20 Debugging C# Code in Visual Studio | Mosh
Debugging C# Code in Visual Studio | Mosh
Programming with Mosh
21 Repository Pattern with C# and Entity Framework, Done Right | Mosh
Repository Pattern with C# and Entity Framework, Done Right | Mosh
Programming with Mosh
22 Angular 2 Tutorial for Beginners: Learn Angular 2 from Scratch | Mosh
Angular 2 Tutorial for Beginners: Learn Angular 2 from Scratch | Mosh
Programming with Mosh
23 Architecture of Angular 2+ Apps
Architecture of Angular 2+ Apps
Programming with Mosh
24 Working with Components in Angular
Working with Components in Angular
Programming with Mosh
25 C# Tutorial For Beginners - Learn C# Basics in 1 Hour
C# Tutorial For Beginners - Learn C# Basics in 1 Hour
Programming with Mosh
26 Difference between Junior and Senior Developers
Difference between Junior and Senior Developers
Programming with Mosh
Step-by-step ASP.NET MVC Tutorial for Beginners | Mosh
Step-by-step ASP.NET MVC Tutorial for Beginners | Mosh
Programming with Mosh
28 [Pluralsight]: Become a Full-stack .NET Developer
[Pluralsight]: Become a Full-stack .NET Developer
Programming with Mosh
29 Xamarin Forms Tutorial: Build Native Mobile Apps with C#
Xamarin Forms Tutorial: Build Native Mobile Apps with C#
Programming with Mosh
30 Value Types and Reference Types in JavaScript
Value Types and Reference Types in JavaScript
Programming with Mosh
31 Using Redux in Angular 2+ Apps | Mosh
Using Redux in Angular 2+ Apps | Mosh
Programming with Mosh
32 Testing Angular 2+ Apps with Jasmine and Karma | Mosh
Testing Angular 2+ Apps with Jasmine and Karma | Mosh
Programming with Mosh
33 Profile and optimize your Angular 2 apps
Profile and optimize your Angular 2 apps
Programming with Mosh
34 Build a Real-world App with ASP.NET Core and Angular 2
Build a Real-world App with ASP.NET Core and Angular 2
Programming with Mosh
35 Entity Framework 6 Tutorial: Learn Entity Framework 6 from Scratch
Entity Framework 6 Tutorial: Learn Entity Framework 6 from Scratch
Programming with Mosh
36 Two-way Binding and ngModel in Angular 4
Two-way Binding and ngModel in Angular 4
Programming with Mosh
37 Udemy Live 2017: Teaching Tech Panel
Udemy Live 2017: Teaching Tech Panel
Programming with Mosh
38 Demo of An E-commerce App Built with Angular, Firebase and Bootstrap 4
Demo of An E-commerce App Built with Angular, Firebase and Bootstrap 4
Programming with Mosh
39 My Brand New Angular Course
My Brand New Angular Course
Programming with Mosh
40 TypeScript Tutorial - TypeScript for React - Learn TypeScript
TypeScript Tutorial - TypeScript for React - Learn TypeScript
Programming with Mosh
41 Access Modifiers in TypeScript
Access Modifiers in TypeScript
Programming with Mosh
42 TypeScript Interfaces
TypeScript Interfaces
Programming with Mosh
43 TypeScript Classes
TypeScript Classes
Programming with Mosh
44 TypeScript Constructors
TypeScript Constructors
Programming with Mosh
45 TypeScript Properties
TypeScript Properties
Programming with Mosh
46 Angular Tutorial for Beginners: Learn Angular & TypeScript
Angular Tutorial for Beginners: Learn Angular & TypeScript
Programming with Mosh
47 AngularJS vs Angular 2 vs Angular 4 | Mosh
AngularJS vs Angular 2 vs Angular 4 | Mosh
Programming with Mosh
48 Angular Material Tutorial | Mosh
Angular Material Tutorial | Mosh
Programming with Mosh
49 Angular Animations Tutorial | Mosh
Angular Animations Tutorial | Mosh
Programming with Mosh
50 Firebase in Angular Applications | Mosh
Firebase in Angular Applications | Mosh
Programming with Mosh
51 Deploying Angular Applications | Mosh
Deploying Angular Applications | Mosh
Programming with Mosh
52 Building Forms in Angular Apps | Mosh
Building Forms in Angular Apps | Mosh
Programming with Mosh
53 Directives in Angular Applications
Directives in Angular Applications
Programming with Mosh
54 Routing and Navigation in Angular | Mosh
Routing and Navigation in Angular | Mosh
Programming with Mosh
55 Angular 4 in 40 Minutes
Angular 4 in 40 Minutes
Programming with Mosh
56 [NEW COURSE] Unit Testing for C# Developers
[NEW COURSE] Unit Testing for C# Developers
Programming with Mosh
57 Unit Testing C# Code - Tutorial for Beginners
Unit Testing C# Code - Tutorial for Beginners
Programming with Mosh
58 C# Classes Tutorial | Mosh
C# Classes Tutorial | Mosh
Programming with Mosh
59 C# Object Initializers Tutorial
C# Object Initializers Tutorial
Programming with Mosh
60 C# Constructors Tutorial | Mosh
C# Constructors Tutorial | Mosh
Programming with Mosh

This tutorial provides a comprehensive introduction to ASP.NET MVC, covering the basics of the MVC pattern, routing, controllers, actions, and views. It also covers the use of tools such as Visual Studio, Resharper, and Bootstrap.

Key Takeaways
  1. Create a new ASP.NET MVC project in Visual Studio
  2. Understand the MVC pattern and its components
  3. Create a custom route in ASP.NET MVC
  4. Use attribute routing in ASP.NET MVC
  5. Use the View method to create a ViewResult
  6. Use the Content method to return content
  7. Use the view data dictionary to pass data to views
  8. Use a view model to pass multiple models to a view
💡 The MVC pattern is a fundamental concept in web development, and understanding its components and how they interact is crucial for building robust and maintainable web applications.

Related AI Lessons

How to Create a Second Version of Yourself Inside Obsidian Using AI (Step-by-Step Guide)
Learn to create a second version of yourself inside Obsidian using AI with a step-by-step guide
Medium · ChatGPT
How to prepare for Spain civil service TIC exam using AI in 2026
Learn how to prepare for the Spain civil service TIC exam using AI in 2026, boosting your chances of success with technology-driven study techniques
Dev.to · David García
Going Viral! How I Created AI Kissing Videos Step by Step Easily Using AIAI.com
Create viral AI kissing videos using AIAI.com in a step-by-step process, leveraging AI technology for creative content creation
Medium · AI
How to prepare TIC teacher exams in Spain with AI (oposiciones 2026)
Prepare for TIC teacher exams in Spain using AI with these actionable steps
Dev.to AI

Chapters (14)

Introduction
2:48 ASP.NET MVC Architecture
5:31 Setting Up the Development Environment
7:38 Your First ASP.NET MVC 5 App
14:34 MVC in Action
21:18 Adding a Theme
26:49 Action Results
31:47 Action Parameters
37:42 Convention-based Routing
42:58 Attribute-based Routing
46:27 Passing Data to the Views
50:30 View Models
54:19 Razor Views
58:38 Partial Views
Up next
AI in Care - Katie Furey, Pairly.com
The Access Group
Watch →