Technology Asp Net Mvc Tutorial Step By Step Pdf


Monday, June 17, 2019

want to learn complete basic with example of MVC 5. . Step 6: Select " MVC 5 View- Empty Without Model" in the Add Scaffold wizard. Step 7: Enter. MVC 5: Building Your First Web Application is targeted to Entity Framework using Database-First approach, learn basic jQuery and This book will guide you through the basic steps on creating a simple web application using . About the Tutorial. MVC is an open-source software from Microsoft. with step-by-step program examples that will assist you to learn and put the.

Asp Net Mvc Tutorial Step By Step Pdf

Language:English, Spanish, Arabic
Country:Korea North
Published (Last):08.10.2015
ePub File Size:26.56 MB
PDF File Size:17.10 MB
Distribution:Free* [*Regsitration Required]
Uploaded by: AZALEE

NET MVC Tutorial in PDF - Learn MVC in simple and easy steps starting from Overview, MVC Pattern, Environment Setup, Getting Started, Life Cycle. This Tutorial is intended for people who are not familiar with MVC. Lab: MVC In this article we learn MVC 5 step by step in 7 days – Day 1., Author. MVC 4. We will be using Visual Studio for the examples in the book. You can use . NET applications is a fairly simple process considering that normally the most MVC 4 tutorials and books base.

If you see the HTML output by doing view source it looks something as shown below. This conversion gets worse and heavy when we have grids.

Due to this unnecessary conversion the response time is less. If you run the above code below are the respective generated HTML. Lot of people can argue that ViewState can be disabled but then we all know how developers are. For detail call us on The size increase is because of extra bytes generated from ViewState. But the main thing is always performance.

Label generates a SPAN. For example see the below ASPX code. NET web server controls. The rest of the three points down below are brownie issues which have cropped up due to presence of code behind and server controls. Literal generates simple text.

The other great benefit of working directly with HTML is that your web designers can work very closely with the developer team. NET WebForm project you will notice that code behind class is where you have huge amount of code and the code is really complicated.

From the code you can know how difficult it is to instantiate the same. In this I started with problems. Below is root cause diagram I have drawn. Someone has to manually run the application and do the testing.

If we have server controls these designer tools do not identify them easily. In other words you can never do something as shown below for a WebForm class: If we read the four issues mentioned in the previous section with ASP.

Reusability of code behind class If you watch any professional ASP. This class is not a normal class which can be reused and instantiated anywhere. How Microsoft Asp. NET classes which you can term as middle layer. As said the code behind and server controls are the root cause problem. In short the solution should look something as shown in the below image. So if you look at the current WebForm architecture which developers are using its mostly 3 layer architecture? For detail call us on The solution is we need to move the code behind to a separate simple class library and get rid of ASP.

Step Model in turn calls the data access layer which fetches data in the model. View is your ASPX i. The code behind logic goes in to the controller. Let us first start with controllers as they are the most important and central part of the MVC architecture.

You can see in the above diagram how those layers fit in. Depending on the action controller creates the object of the model.

NET classes termed as controller. This data filled model is then passed to the view for display purpose. The first hit comes to the controller.

View and Controller. So what exactly can be this logic? Some logic?? What is User Interaction logic?? Scenario 1 Did you ever gave a thought what happens. HTML response which can consist of couple of input controls and a submit button. By means of such request. Browser sends request to server and server sends a response. Net MVC? In order to understand Controller first we need to understand this term User interaction logic. Server is able to respond back because some logic is written at server end to fulfill this request.

For detail call us on Understand Controller in Asp. In Asp. Step 1. This time the difference is. Put Name. Input controls etc. Normally in technical world layer defining the user interface design is termed as UI layer and in MVC it is termed as View.

HTML with some images. Most commonly the response is HTML as browser understands that format much better. Put Location and say ok. In case of Asp. In short there must be some user interaction logic written on the server. Understand Views in Asp. Net Web Forms Microsoft wrote some code on behalf of us and brought us the feeling of event driven programming.

For detail call us on Step 1. Step 2 — Create Controller Step 2. Click ok. We will talk about it in detail soon. Make sure not to delete the word controller. In the solution explorer. MVC follows Convention based approach. When you type the controller name on the URL it should be without the word controller. Net Web Forms. Net MVC two things are very important. Execute and Test Press F5.

For detail call us on Step 3. TestController is the class name whereas Test is the controller name. How we name something? Where we keep something? What is Action Method? In above example. For detail call us on do response. What will happen if we try to return an object from an action method? Look at the following code block.

What if you want to get values of properties in above example? Output will be as follows.

For detail call us on Is it must to decorate action methods with public access modifier? Yes, every public method will become action methods automatically. What about non-public methods? They are simply methods of a class and not available publicly. In simple words these methods can not be invoked from the web. What if we want a method to be public but not action method? Simply decorate it with NonAction attribute as follows.

Lab 2 — Demonstrating Views In the first lab we created a simple MVC application with just controller and simple string return type. Let us go add view part to the MVC application. Step 1 — Create new action method Add a new action method inside TestController as follows. Step 2. For example: Views associated with the particular controller is placed inside a special folder. Test and Execute Press F5 and execute the application.

For every controller only those views will be available which are located inside its own folder. For detail call us on Views located inside this Shared folder will be available to all the controllers. In MVC 5 support for aspx view engine is removed.

Based on the extension of the view. This HTML string will be returned to the end user. In MVC views and controllers are not tightly coupled. Look at the following code. Is it possible that one action method is referencing more than one views? In the above example we have not used any razor syntaxes hence in this case ViewEngine just take the View and return the same as it is.

Awards & Recognitions

One action method can refer more than one view and one view can be referred by more than one action method by keeping them in Shared folder. It provides better reusability What is the purpose of View function? View function is defined inside controller base class. What is ActionResult? What is the relation between ActionResult and ViewResult? Is it possible to invoke View function without Parameter?

Net MVC when end user makes a request to an action method. To achieve polymorphism. What is ViewResult? Multilevel because. For detail call us on ActionResult encapsulates response of a user request. Look at the following example. What is ContentResult? ContentResult is also the child of ActionResult.

Difference is ContentResult is an ActionResult wrapper around string result. In real life scenario it will display some dynamic data. View will get data from the controller in the form of Model. Model In Asp. Controller will add items to this dictionary and view reads from it. Make sure to put using statement in the top or else we have to put fully qualified name of employee.

Net MVC model represent the business data. In the next lab we will display some dynamic data in the view. It means Display First Name followed by a space and then last name.

Why casting is required? ViewData holds objects internally. Write emp. Test the output Press F5 and test the application.

Every time a new value is added into it. Employee ViewData["Employee"]. LastName Why hardcoded Employee class is created in Controller? FirstName emp. For detail call us on Step 4. Retrieve the Employee data from the ViewData and display it as follows. FirstName can be replaced with following code snippet. In the last lab emp. So unboxing is required every time we try to extract value out of it. Can we write same thing with single keyword?

ViewBag uses the dynamic feature of C 4. Employee ViewBag. For detail call us on Just for demo purpose. ViewBag internally uses ViewData. ToString "C" Step 3. In real time we will get it from may be database or wcf or web service or may be from somewhere else. As a good programming practice. Vice versa is also possible. Data type of values inside ViewData. No Type safety and no compile time errors If we try to cast values to wrong type or if we use wrong keys while retrieving the values.

As I said before. It leads to many run time issues and inefficiency in development.

Performance issues Values inside the ViewData are of type Object. Lab 5. We have to cast the value to correct type before using it. Complete unawareness. In MVC. We can. Now when Developer writes a View.

If Controller developer is different from View developer then it becomes even more difficult. It adds additional overhead on performance. ViewBag is just a syntactic sugar for ViewData.

If salary is greater than then it will be displayed in yellow colour or else green colour. Employee Above statement make our View a strongly typed view of type Employee. FirstName Model. This time we will take our View requirement to next level. Add UserName property to Employee class — Every time we want to display new data in the view.

This new property may or may not be related to Employee. We have done following three things which purely violates MVC architecture rules. Understand View Model in Asp. As a best practice always make the view a strongly typed view. Can we make our View a strongly typed view of more than one model? ClassName in View every time? V that is View should be pure UI. In real time project we often end up at a point where we want to display multiple models in same view.

Solution for this requirement will be discussed in next lab. It should not contain any kind of logic. Let say we have situation where we want to display more than one kind of data in the View. According to MVC. Current User Name should also be displayed in the view as well Create a new class called EmployeeViewModel inside ViewModels folder will looks like below.

How View and ViewModel will be connected here? View is going to be a strongly typed view of type ViewModel. Model is Business specific data. First Name and Last Name should be appended before displaying 2. How Model and ViewModel will be connected?


Model and ViewModel should be independent of each other. Net MVC application. For detail call us on ViewModel a solution ViewModel is one of the unspoken layer in the Asp. Amount should be displayed with currency 3.

It will be created based on the View. How it works exactly? ViewModel is View specific data. Salary should be displayed in different colour based on value 4.

Controller will create and initialises ViewModel object based on one or more Model object. It will be created based on Business and Database structure. Hello Model. Data type of Salary property is string and two new properties are added called SalaryColor and UserName. ToString "C". Is it a good practice to have some relationship between Model and ViewModel? So better if we keep a provision from the beginning and Create ViewModel. Every View will have its corresponding ViewModel. Talk on Lab 6 Does it means.

In this case. For detail call us on vmEmp. Problem will be. Every view should always have its own ViewModel even if ViewModel is going to contain same properties as model. Should we always create ViewModel? We should always create ViewModel. For detail call us on In this lab, we will take our project to next level. We will add Business Layer to our project. LastName; empViewModel. For detail call us on if emp. Yes, we can. Managing future presentation logic. Secondly UserName property.

UserName is not associated with individual employees. It is associated with complete View. UserName is going to be same for all the employees.

Keeping UserName property inside EmployeeViewModel just increase the redundant code and also increases the overall memory requirement for data. First Lab of Day 3 will be all about database and database layer. What is Entity Framework in simple words?

When we think about any data driven application we end up with following two things. ORM is a tool which will automate these two things.

Entity framework is Microsoft ORM tool. What is Code First Approach?

In Entity framework we can follow one of these three approaches 1. Database First approach — Create database with tables, columns, relations etc. Model First approach — In this approach Model classes and relationship between them will be defined manually using Model designer in Visual studio and Entity Framework will generate Data Access Layer and Database with tables, columns, relations automatically.

Relationship between those classes will be defined by means of code. When application executes for the first time Entity framework will generate Data Access Layer and Database with tables, column and relations automatically in the database server.

ASP.NET MVC Web Applications and Foxit Quick PDF Library

What is mean by POCO classes? POCO classes means simple. Net classes we create. Search for Entity Framework and click install. Step 4 — Create Data Access layer. Add EmployeeId property in Employee class and mark it as Key attribute.

ToTable "TblEmployee". OnModelCreating modelBuilder. It automatically get created in runtime. Now change GetEmployees method class as follows. Put using statement in the top.

For detail call us on Step 5 — Create primary key field for employee class Open Employee class and put using statement at the top as follows. Check the database. Step 10 — Execute and test the application Press F5 and run the application again.

Now we have a table called TblEmployee with all the columns. How connection string and data access layer is connected?

Mapping will be done based on name. Can we change the ConnectionString name? When we write a Linq query again DbSet object it internally converted to query and fired against database. DbSet simply represent the collection of all the entities that can be queried from the database. In simple words.. For detail call us on First Name: Request may be one of the following four types. How making request using Form tag is different from making request via browser address bar or hyperlink?

It follows request-response model. What is method attribute in Form tag? It decides the type of request. As soon as the submit button inside form tag gets clicked. End user make the request and server sends response.

For detail call us on When request is made with the help of Form tag. How values will be sent to server? When request is of type Get. Will values of this controls also sent?

Submit button will be specially used when we want to make request to the server whereas simple button will be used to perform some custom client side actions. Does name and id attribute serves same purpose?

It makes server receive more than one value at a time. Put or Delete. What is the purpose of name attribute in input controls? As discussed before values of all input controls will be sent along with request when submit button is clicked.

What about checkbox. Will Model Binder work with composition relationship? Yes it will. What will happen when two parameters are specified. When match is found. FirstName property. When match is found..

FirstName will be updated in both primitive FirstName variable and e. For detail call us on Talk on Lab 10 How Textbox values are updated in Employee object inside action method?

Hence value of the submit button which is responsible for the request will be sent too. We know that. When Save button will be clicked. Model Binder will do remaining work. For detail call us on return new EmptyResult. I would like to discuss three of them. Along with the request values of all the input controls will be sent. Press F5 and execute the application.

In Action method. It will update the parameter values with values in input data coming with request What are the other ways to implement multiple submit buttons? There are many ways. Submit button is also an input button. LastName and Salary. Form syntax and manually construct the Model object as follows. What if names are not matching with property names of the classes? This is a very common question during interviews. Ajax Instead of submit button use simple input button and onclick of it make pure Ajax request using jQuery or any other library.

For detail call us on Step 1 — Create a hidden form element in View as follows. ModelBindingContext bindingContext. Parse Request. What does RedirecttToFunction do?

Parse controllerContext. SaveEmployee e.

Related Books

What is EmptyResult? One more child of ActionResult. It represents the redirect response. Navigate to Data entry screen and put some valid values. When ActionMethod return type is Void. Just to make sure that all code paths returns a value EmptyResult statement was written.

When browser receives EmptyResult as a response it simply displays blank white screens. Add e. When browser receives RedirectToRouteResult. Let understand a little more about same. Before we get into Data Annotation lets understand few more things about Model Binder How Model Binder work with primitive datatypes When Action method contain primitive type parameter.

If null assignment is not possible. IsValid will be set to false. Model Binder will compare name of the parameter with each key in the incoming data Incoming data means either posted data or query string. How Model Binder work with classes When parameter is a Class parameter.

Model Binder will iterate through all properties of all the class and compare each property name with each key in incoming data. ModelState["FirstName "]. Default value — For integer it is 0 zero.

ModelState encapsulates the state of the Model. Model Binder also updates ModelState. In this case ModelState. IsValid will be set to false IsValid will remain unaffected.

As you can see. When ModelState. For detail call us on Note: You may end up with following error. Validates the value against a particular regular expression. ValidationMessage is a function. This article is intended to MVC and we are try to stick with it: Talk on lab 13 What does Html. As we discussed earlier. Do we have more attributes like required and StringLength?

URL etc. Consider using Code First Migrations to update the database. How Salary is getting validated? Is that means. ValidationMessage do? IsVaid will be false and ModelState will hold validation error related to Salary which will displayed in view because of Html.

Database class exists inside System. Now in this case. Model Binder updates the ModelState. In Test 1 — we had kept salary as empty string. Entity namespace Soon we are going to start a detail series on Entity Framework Code First approach where will speak about this in detail. Reason for that is. It executes at runtime. ValidationMessage displays the error message from ModelState based on Key.

Model Binder also considers the datatype of a property while updating model. DataEntry view which was rendered in the beginning and which get rendered later are same from development perspective but are different from request perspective. IsValid will not be of any use. In this case we can use UpdateModel function as follows. Can we explicitly ask Model Binder to execute? Yes simply remove parameters from action method. It stops default model binder from executing by default.

We will learn how to maintain values in Day 4. TryUpdateModel will be same as UpdateModel except one added advantage. We are going to talk about both manual client side validation and automatic client side validation with the help of HTML helper classes in day 4. TryUpdateModel is exactly same as keeping Employee object as function parameter.

IsValid will be false. UpdateModel will throw an exception if Model adaption fails because of any reason. In case of UpdateModel function ModelState. What if we want to have a non-required integer field? Make it nullable? If updating fails ModelState. Why values are getting cleared when validation fails? What about client side validation? In that case both validations will fire. For detail call us on Yes. We achieve the same by using our own validation like regular expression.

Can we attach more than one DataAnnotation attribute to same property? Yes we can. Execute it and understand the code and output both perfectly. In the Lab 15 we will learn how to repopulate values on validation failure. I strongly recommend you to rerun to the Lab 14 once again. Change SaveEmployee Action method as follows. For detail call us on vm. Step 3 — Execute and Test Press F5 and execute the application.

It will make two validations fail As you can see 56 is maintained in Salary Textbox. For detail call us on Reason for above error will be discussed at the end of this lab. Do we have any automated way to achieve same functionality? LastName length should not be greater than 5. For detail call us on As you can see FirstName and LastName textbox values are maintained. We will talk about this in one of the upcoming lab.

Talk on Lab 15 Are we really retaining values here? FirstName should not be empty. Earlier in this action method we were returning view without passing any data. In the View we are trying to populate textbox with the values in model. Salary should not be empty. Salary should be a proper number 5. Here we are actually repopulating the values from the posted data.

It means Model property inside view be Null and Null. If Model is null. For detail call us on return 'Enter valid salary'. We will make sure that only valid user will be able to access the action method. In case someone disables JavaScript. Server side validation keep everything in place. We will discuss this in one of the future lab Does server side validation is required anymore? In our case IsValid function will return false when validation fails and thus we achieve desired functionality.

There is no point on making server request when validation fails. Simply create a span tag for each error. Instead of alert can we show the error messages in the page itself? For detail call us on Test 1 Test 2 Talk on Lab 16 Why return keyword is required in onclick of SaveEmployee button click? As we discussed in Lab 9. Make it invisible using css in the beginning and on submit button click if validation fails make it visible using JavaScript.

Is there any way to get this client side validation automatically?

ASP.NET MVC Generate and Print PDF using Rotativa MVC

We understood that Asp. Net are inherited in Asp. One of the feature is Forms Authentication. Most of the features of Asp. For detail call us on In the Day 1 of this series we understood the real meaning of word Asp.

Browser will send all the associated cookies stored in the client machine with request. Net MVC is part of Asp. End user make a request to Forms authentication enabled application with the help of browser. Make it a strongly typed view of type UserDetails.

Net 1. Step 1 — Create AuthenticationController and Login action method. If valid authentication cookie is not found server considers user as anonymous or unauthenticated user. Inside controller create and Action method called Login as follows. When request is received as server end. If valid authentication cookie is found. Password Html. BeginForm "DoLogin". Example 1: UserName Html. Find a child section called Authentication. Web section.

Open EmployeeController and attach Authorize attribute to Index action as follows. Step 7 —Execute and Test Press F5 and execute the application. In the address put the URL of Login action method. Navigate to System In real time we can make call to Database layer and compare it with real time values.

AddModelError "CredentialError". In business layer we are comparing username and password with hardcoded values. If user is a valid user create an authentication cookie. This error will be displayed in View. It makes futures requests authenticated request. It contains all the errors related to current model. SetAuthCookie u. If user is invalid. Check for validity of user by invoking business layer function.

Directly make a request to Login Action. For detail call us on Step 10— Display message in view Open Login View and add following code just above the Html. If you want you can make request to Index action of EmployeeController but it ultimately redirect you to Login Action. ValidationMessage "CredentialError". I believe you know how to do it now.

This attribute makes DoLogin action method open for only Post request. BeginForm Html. To keep coding and learning simple and easy we have not followed such practice everywhere in this series but I recommend you to strictly follow it in your project. To solve this issue Server will add a cookie in the prepared response and send back. Open Web. Is it must to write FormsAuthentication. As a best practice every action method must be attached with such attributes.

We have HttpGet. As we move along we will keep on talking about such best practices. HttpPut and HttpDelete.

We have an alternative for it. For detail call us on Do we have more such attributes? We can use URI instead of cookies.

They will repopulate the values in the controls from the posted data. SetAuthCookie do? It will decide whether we want to create a persistent cookie or not. Persistent cookies wont deleted automatically. We will discuss each one of them in our 7 days journey.

What does Authorize attribute do? We have to remove it manually either via coding or by using browser settings. There are four kind of filters. Non persistent cookies will get deleted automatically when browser is closed. It means authentication works via cookies and in case cookies are not supported URL will do the required work.

It will make sure that only authenticated requests are allowed for an action method. What does second parameter of FormsAuthentication. What does Html. This is one of the advantage of using Helper classes.

Which will be used to filter out requests and response. How come the UserName textbox is repopulated when credentials are wrong? ValidationMessage does? We already discussed it in Lab 13 talks. Right click under the Index action and click on Add View. Add the following code to Index.

Add the following code under HomeController partial class. Also change the version number, we have used version Also create the CreatePdf action in HomeController class. Under CreatePdf action add the following code. Add the highlighted code under Index action. You will run into permissions issues if you try to use functions such as SaveToFile to save files into the root directory of your project.

SaveToFile Server. Run the Web Application and you will see the library version used. Sample Code This is only code for the HomeController. Generic; using System.RenderAction is recommended because it is faster. If salary is greater than then it will be displayed in yellow colour or else green colour. Thanks Scott, That's very nice. Anirban Das. Hi Scott Gu, Great work again. Sandesh M Patil Feb Open Index.

Licenced CPOL. Partial return MvcHtmlString instead of string? What will happen when two parameters are specified.