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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

This isn't really a step by step, is it? This is a snippet from your udemy course used as advertising.

I was also expecting not working from a Microsoft project template as a lot of stuff is in it that you really don't need or want lots of the time.

👍︎︎ 1 👤︎︎ u/[deleted] 📅︎︎ Jun 01 2016 🗫︎ replies
Captions
hi welcome to the complete ace phenomenal MVC course my name is Mohammad Ani 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 Weebly and it's supposed to be used at video rental stores we have two different roles here admin and staff member let me login 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 a 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 crud 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 customers but let me show you something if I log out and log in as a guest or staff member and by the way we can log in with Facebook as well so with what you learn in this course you can easily extend this application and add support for Google and Twitter authentication let's login now back in the list of movies I get a read-only view of the list of movies I cannot add update or delete a movie so these features are only available to admins now with the list of customers and movies in the database you can add a new rental so when a customer comes to the counter we look them up here and then we add all the movies are going to rent and again here we have another business rule these movies have limited availability so as we are renting out these movies we need to keep track of availability of movies so once again this application is more than just crud so are you excited to build this application with me I hope you are let's 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 a spoon and an NBC is one of them there are many other similar MVC frameworks like Ruby on Rails or Express for note in an MVC 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 are not tied to the user interface which means we can take these classes and use them in a different kind of app like a desktop or a mobile app they are playing old CLR objects or pocos v in MVC represents the view and is 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 vidlink comm when we send a request to vit lucam slash 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 isn't really 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 slash movies should be handled by class called movies controller more accurately it should be handled by one of the methods of this class because the class can have many different methods in asp.net 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 a sudden MVC in three minutes okay 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 plug-in in your case you will see a button to install this plugin and the last plug-in 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 resharper is a commercial plug-in and the price is somewhere about 70 to 90 dollars 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 for 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 resharper 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 resharper 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 sharp and web and here select asp.net web application I'm going to call this bitly and store it in my C Drive and the projects folder now here you see add to source control is selected because I'm going to add this to get if you don't have get on your machine or you don't want to add this on your source control don't worry about this so on tick the check box okay now here in the list of templates select MVC I'll 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 say this dialog box where I can select either team foundation version control or TFS or git I'm going to select get 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 on the line data which is where our database file will be stored we have app on the line 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 we send the request to slash movies slash popular it's not the runtime we'll call a method or an action called popular in movies controller or as another example if it's on the request to slash movies slash edit / is not 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 round 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 slash movies since the action name is not specified in the URL it will be indexed in movies controller also you can see that ID is an optional parameter because not every action needs an ID we only need this when we're working with a specific resource like a movie or a customer with the 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 logout home which represents the home page and manage which provides a number of actions for handling requests around users 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 root 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 names 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 asp.net will look for that view in a folder with the same name as the controller we also have a folder called share it which includes the views that can be used across different controllers and finally we've got a few other files here fav icon is the icon of the application displayed in the browser global a si X 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 applications lifecycle so let's expand this and open the c-sharp 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 is started we tell the runtime these are the routes for our application next we have packages that config which is used by NuGet package manager if you have never worked with NuGet it's a package manager similar to NPM or node package manager or Bower if you'll never works 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 that CS which is a new approach Microsoft is taking for starting the application so the next version of asp.net called asp.net core 1.0 which is not ready yet they've dropped global data ax and all this sort of logic is implemented in this startup class and finally we have web config which is an XML that includes the configuration for our 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 appsettings 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 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 snippet 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 slash movies slash 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 auto generating 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 very simple class that derives from the controller class 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 slash movies slash random now in this method I'm going to create an instance of our movie model so a movie new movie now because I'm using resharper resharper automatically resolved the namespace for this class if you're not using resharper you need to go on top of this file and manually type using vit Lee dot 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 auto generate a view but we're not going to use this feature under options you can tick 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 untick here we have a check box 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 fault our MVC 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 see sharp code prefixed with an ad sign so on the top you have a block and inside this block we are setting two properties one is view back the title which we'll look at later but basically this is going to be the title of our page shown in the browser an expert 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 ctrl + tab this way we can switch between open tabs look view is no longer read because now we have a view on the disk now I want to put this model movie model in our view so we can render it again ctrl 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-sharp code we start with add sign and then type model every view has this property which gives us access to the model we pass to it in the controller now in the intellisense note that the type of this model is dynamic it's not a movie so if I use the dot 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 a design 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 widly that models that 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 name space 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 we press ctrl + f5 now our browser will take us to slash movies slash random so ctrl f5 okay congratulations so you have seen a model a view and a controller in action throughout the rest of the course will 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 asp.net MVC application uses bootstrap as its front-end CSS framework so to replace this template we need to find a bootstrap template head over to boots watch comm here you see a bunch of different templates for bootstrap under themes select lumin so scroll down our navigation bar will look like this here we can see the buttons tables forms so nice and clean now under Newman select bootstrap dot 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 - lumen to distinguish from the original bootstrap file then add it in the project under the content folder so here you see I have both bootstrap and bootstrap - lumen now we need to replace the reference to bootstrap with bootstrap lumen so on our app on the line 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 into a bundle and this way we reduce the number of HTTP requests required to get these assets when a page is loaded at this result in a faster page load so here you see we have a few bundles one for jQuery and inside this bundle we have the jQuery script we have another bundle for jQuery validation plug-in and inside this bundle we have all the files that match this pattern we have another bundle from moderniser one for bootstrap and another one for our CSS assets in our CSS bundle we have bootstrap and site dot CSS which includes a few generic styles for our application now ad - lumen here now because we have modified our c-sharp code we need to compile it in order to see the changes so press ctrl + f5 to compile and run the application again alright here's our new home page with a new look and feel 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 a nice banana 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 on a spinet an MVC in detail by the end of this section you will have a good and in-depth understanding of how a speed and an MVC works next we'll use entity framework to connect our application to a database they'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 crud operations in asp.net MVC next we'll look at using asp.net Web API to build restful services so I will explain what restful convention means and how you can create restful services using asp.net Web API once we build our API s we'll shift our focus to client-side development so we'll use jQuery to consume some of these API so in this section you're going to learn about two very useful jQuery plugins next we'll implement authentication and authorization using a speed and identity framework so you will understand exactly how a speed and an 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 ten 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 will learn about building and deployment so there is a lot to cover and I will see you in the next section well hello it's mahshar your instructor I just wanted to let you know that what you've been watching so far is actually picked from my complete a spoon and nbc5 course on udemy 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 in this section we're going to take a closer look at building blocks of a Sweden ATM receipt 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 controller's actions routing views and view models so let's get started so in the last section you noticed that our random action returns an action result this action result is the base class for all action results in asp.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 a speed-up 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 good practice especially when it comes to unit testing this action this way will save ourselves from an extra cast in our unit tests we 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 if your result is one of the action results that you work with most of the time let's 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 a rapt result to redirect 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 and 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 em to 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 ctrl + f5 and navigate to slash movies slash random so look we just get plain string contents in the response another example let's return HTTP not found now build the application with ctrl shift B this will compile the application without opening a new tab in the browser now press Alt + tab to switch back to Chrome and ctrl R to refresh the page okay look we got this standard 404 error now for empty 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 ctrl shift B to build Alt + 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 1 and sort by is name build back to Chrome refresh okay look we got redirected to the home page and you can 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 these 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 a 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 MVC 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 control shift B on 10 tab back to the browser I'm going to change the URL to movies slash edit / 1 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 ctrl L I'm going to change this to ID equals 1 it gets mapped again but let's see what happens if I rename this parameter to movie ID to rename you press f2 so all references are renamed automatically movie ID one more time billed back to the browser refresh we got an exception the parameters dictionary contains a null entry for parameter movie ID so if not the NBC 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 rap 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 smelvin MVC Maps requests data to parameters 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 we'll 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 1 and similarly if sort by is not specified we sort the movies by their name now to make your parameter optional we should make it non level so for page index I'm going to add a question mark here to make it an honorable integer and four sort by we don't have to do anything because the string type in c-sharp is a reference type and it's not able now inside the action we check to see if these parameters have a value so if page index has value I put the nut operator here so if it doesn't have a value I initialize it to 1 similarly if string is null or whitespace 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 that 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 its name I can override this parameter so I can pass page index set it to two and you can see it's updated here a sort by is still name I can overwrite that to 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 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 this route 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 named URL and defaults so let's give our new router 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 movies slash released 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 anonymous object here we set the name of the controller to movies and the action to by 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'll show you a quick way to create an action type MVC action for and press tab so this is another code snippet so 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 here plus slash plus month now build back to the browser let's navigate to movies slash released I'm not specifying any parameters we got a 404 error because our URL has not matched any of our rap patterns now let's put the year and the month so our ramp 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 a rap 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 digit number so set it to a verbatim string backslash D which represents a digit and the number in curly braces represents the number of repetitions the reason I put an add sign here is because backslash is an escape character and if you don't use app sign here we'll have to add another backslash and this looks a little bit ugly so undo that's better now similarly I'm going to set months to a regular expression backslash D with two digits billed back to the browser 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 constrain 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 route in a snap that M you see 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 customer out here but if you're working on a larger 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 string in asp.net MVC five Microsoft introduced a cleaner a 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 Marsh why did you teach me the old and poor way of creating custom routes because you may be working with an existing code base 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 dot map MVC attribute routes I 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 released slash here slash month now to apply a constraint got colon and then we add regex to apply a regular expression this is like a function that we call in parentheses 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 regex colon again this time I'm going to use range to set the 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 lengths for Strings integer float quit and so on you don't have to memorize any of these constraints just be aware that they are supported by the framework if you need to apply constraints to your attribute routes just Google asp.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 and its 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 ctrl b and it's drop down you see the name of the view random that CS 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 code is going to get a little bit ugly that's what I meant so all these noisy parentheses compare this to what we had before model dot 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 into view and make this change here as well otherwise we'll get a null reference exception so this way of passing data to the views is fragile we had this in the very first version of MVC and then Microsoft decided to improve this but in a very poor way so they introduced view back which is a dynamic type so back in the controller instead of using view data with a magic string we use viewbag with a magic property so this movie property is added to the view back 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 into view and change it here plus we'll have the casting issue as well so honestly I have no idea what Microsoft was thinking when they introduced this view back 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 your result your result that view data 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 a 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 viewmodel so as a convention we use the viewmodel suffix this class needs two properties one is the movie note that as I type the movie here resharper automatically added this namespace here the other property is a list of customers now let's go back to our controller in the random action I'm going to quickly create a list of customers use the object initialization syntax to add to customer objects here customer 1 and 2 now we create a view model object random movie view model again resharper automatically resolved 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 property so we change it to model the movie thing and you can see here we have access to model that 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 review syntax in asp.net MVC so you have learned that here we can write C sharp code by prefixing it with an axe 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 a speed added 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 can either continue writing c-sharp 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-sharp so at sign customer dot 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 that customers that 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 Razr of your 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 you can see working with razor views is pretty easy now let me show you a few more techniques let's say here in H do 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 at sign code block here we can write any sushar code so I'm going to declare a variable call it class name and initialize it like this if model that customers the count is greater than five it should be popular otherwise it should be known 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 ctrl f5 okay right 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 recompile the application because this is just a view so we can switch back to the browser refresh 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 @ sign and we can make it multiple lights this is a comment on multiple lights so earlier when we created the 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 share it lay out 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 all down control and press M twice below this navbar we have a container for our pages note this call to render body method 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 the 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 but extracting the part that represents the navigation bar into a partial view so let's do that back in solution Explorer right-click shared add view by convention we prefix partial view names with an underscore so let's call this underscore navbar we need to tick this check box here create as a partial view this way this view will not have a layout okay now roll tab to get back to the layout scroll up a little bit so here's our navbar element again put the cursor on this element hold down the ctrl and press M twice ok collapsed control eggs to cut - navigation bar paste it here now we can see in this partial view we only have a navigation bar nothing else so next time we want to change something on our navigation bar you 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 use add sine 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 underlined 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 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 pass through 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 dot movie okay we've covered a lot of ground about various components of a snap than 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've learned in action okay I want you to use what you have learned in this section and implement a few simple features in our video app so you can see here on the navigation bar I have changed the application name to read Li and now we have only two links customers and movies in the customers page we have a table with a list of customers and currently we have only two customers now these customers are not coming from a database I've just hard coded them in my action for this exercise don't worry about the database in the next section we're going to use an entity 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 slash details slash one which is the idea 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 a customer with that ID now in the future we can replace this pouring standard page with a custom design before 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 hard coded movies Shrek and wall-e and there is 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 if you want to see my solution you can simply head over to github.com slash Maj - gamma daddy here you see I have a repository created for this course lately - MBC - five 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 commit it 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 split because it's easier to see the before and after changes so we can see in layout dot CSS 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 remove this div which was our navigation bar and replace it with HTML that partial method let's scroll down here is another file nav bar that's es HTML which is a new file because previously we had nothing here I know we've got all this markup for the navigation bar so you can see I've got another comment here solution section to 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 module you learn the fundamentals of a speed up an MVC or specifically you learn about action result action parameters convention based routing attribute routing and raiser views in the next section we're going to use entity framework and connect our application to a database so I will see in the next section well if you made it this far you seem to be very enthusiastic about learning asp.net MVC 5 and I highly recommend you to take my complete a splat an MVC 5 course on udemy this course contains seven and a half hours of content in terms of high-quality video and audio along with lots of exercises and real-world examples if you're interested you can get the course with a discount using the link in the video description I hope to see you in the course
Info
Channel: Programming with Mosh
Views: 2,847,866
Rating: 4.882987 out of 5
Keywords: c#, .net, asp.net, asp.net mvc, mvc, repository pattern, tutorial, entity framework, c#.net, visual studio, code with mosh, programming with mosh, asp.net mvc framework (software), model view controller
Id: E7Voso411Vs
Channel Id: undefined
Length: 67min 49sec (4069 seconds)
Published: Sat May 28 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.