Showing posts with label Asp.net MVC. Show all posts
Showing posts with label Asp.net MVC. Show all posts

Sunday, 18 February 2018

In this article, I will explain How to create first application in Asp.net MVC.

Step 1: Download and install visual studio community Edition from this link which is free  https://www.visualstudio.com/downloads/  .Remember Visual studio is IDE(Integrated development Environment)

Step 2 :  Open visual studio and Go to File->New ->Project


Step 3 :  Select Web->Asp.net web Application and enter project name and browse project location and hit Ok


Step 4 : Select MVC  and Leave uncheck to Add unit tests


Step 5 : Select No Authentication for this first application .we will discuss it later.Hit OK and again hit Ok


Step 6 : Now project will open and structure of our project looks like below


Step 7 : Delete HomeController.cs file because we are creating from scratch.


Step 8 : Delete Home folder inside view .Views->Home


Step 9 : Add Controller .For this Right click on Controller folder->Add->Controller


Step 10 : Select MVC5 Controller-Empty


Step 11 : Enter controller name as Home and do not delete the word controller.MVC works on convention so we always write controller name as HomeController. i.e. we append word controller.For now word controller is just like reserve word.Hit Add


Our controller code is shown below . Here Home is controller name and HomeController is class which is inherited from controller base class which is present inside System.Web.Mvc namespace.Inside HomeController class there  is Index action method which is always public whose return type is ActionResult(ActionResult is abstract class) . But here we are returning View() which  returns  ViewResult  class.This ViewResult class is inherited from  ViewResultBase and finally this ViewResultBase is inherited from ActionResult so ViewResult class is indirectly inheriting from ActionResult abstract class .Return type of action method is not always ViewResult so we make its reutrn type as base class ActionResult which is parent for different action results like JsonResult, PartialViewResult, ContentResult, FileResult etc.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DemoApp.web.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}
Step 12 : Now Run our application .Debug->Start without debugging


Step 13 :  When  we run our application it displays following error  because we have not created any view yet. View name is same as action method name in mvc and it searches with different file extensions  inside folder whose name is same as controller name and finally inside Shared folder.If we want to share our view among different controller's action method ,we should put that view inside Shared folder.Here View is not present inside Home and Shared folder so displays  error.


Step 14 : Now add view . Right click anywhere inside curley braces of action method and click add view .Leave view name as it is and view name is same as action method name but you can change the view name according to your choice .If we change the view name we should called explicitly call that view from action method giving its name as parameter to View("view name").Select Empty(without model) template for now and leave blank model class.Tick use layout page for setting common design to child page as well. Here Layout page is same as master page in asp.net webform. and finally hit Add


Step 15 : now Our view looks like below  and write <p>Hello World !!!</p> inside view
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<p>Hello World !!!</p>


Step 16 : Routing simplifies the URL. We have to write name as key ,url and defaults controller and action name  inside MapRoute method.Here Default is our key,url pattern is controller name /action name/ id (which is optional) . In our case Home is default controller and Index is default action.


Step 17 : Final output is as shown below .


Mvc is an architectural pattern that divides an application into three interconnected parts where as asp.net MVC is web application framework developed by Microsoft on the top of asp.net framework(Asp.net is part of .Net framework) for creating web applications which implements MVC(Model -View-Controller) pattern.
ASP.NET Web Form was a replacement for Microsoft’s Active Server Pages (ASP) but ASP.NET MVC is not a replacement for ASP.NET Web Forms and it’s just an alternate way of making an ASP.NET website.

ASP.NET MVC is open source!- In March 2012, Scott Guthrie announced ASP.NET MVC, Razor and Web API under an open source license (Apache License 2.0).

Request flow in Asp.net MVc :
1) When end user hits a URL on browser,the request is sent to the server through browser and this first request is received by controller (User interaction logic is handle by controller)
2) Controller request to the model for information and Model in turn calls the data access layer which fetches data in the model.
3) Finally controller updates view according to model and end user gets response as view .
Why Asp.net MVC

1) Follows Separation of Concerns Philosophy
   i)Components are only responsible for one thing
   ii)Loosely coupled
   iii)Modular components
2) Clean URL
3) Full Control Over the User Interface or the HTML
4) Better For Search Engine Optimization
5) Loosely Coupled so Each Component can be tested independently. Better Support For Test Driven Development.

Problems in Asp.net Webform
1) View Based architecture for an Action Based requirement.
HTTP protocol is action oriented that means when end user sends requests(i.e. actions) and get response .In asp.net web form when we want to perform an action by clicking on button,the request is sent to view(page having .aspx  extension)  which kicked off behind code having complicated page life cycle and finally executes the logic written in button click event.But in asp..net mvc end user request is directly sent to action within controller and depending up the logic it calls view.

2) Behind code is not reusable
Code behind page(page having .aspx.cs extention) in asp.net webform  is not reusable  but in asp.net MVC code behind logic is written in action of controller so same logic can be used for different view. 
 


3) Bandwidth consumption
Viewstate of asp.net webform generates extra bytes  which consumes more bandwidth even  it automatically saves states between post backs and reduces our development time.

4) Slow Response time
Browser can understand only HTML so every server controls of asp.net webform should be converted into HTML and there is some conversion logic in server due to which response time of asp.net webform is slower than asp.net MVC.


5) Default return response is always HTML
In asp.net webform default response time is HTMLso if we want to get string response we should create HTTP handler.But in Asp.net MVC it is very easy just return string.
References :
1) https://www.questpond.com/
2) https://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day

Monday, 22 January 2018

Introduction:


 In this article, I will explain How to implement paging using PagedList library in Asp.net MVC.

Step 1: Open visual studio Ã  Go to File menu Ã select New Ã  Project like as shown below


Step 2: Now from web templates select Asp.Net Web Application (.NET Framework) and give name (PagingInMVC) to the project and click OK button like as shown below.

Step 3: Once we click OK button new template will open in that select MVC from templates like as shown below

Step 4:Our project structure will be like as shown below


step 5: Delete the HomeController already present in the project because we will create it from scratch as shown below

Step 6: Delete the Home folder inside Views folder as shown below

Step 7 : Design database and table like shown below :


Step 8 Click on Models -> Add ->New Item as shown in below


Step 9: Select Data -> ADO.NET Entity Data Model and give name PagingModal and click add as shown below


Step 10: Select EF Designer from Database and click next as shown below


Step 11 : Enter server name (local) or your live server name and select database name and test the connection and click Ok as shown below

Step 12 : Click  Next as shown below

Step 13 : Select Next  as shown below

Step 14 : Tick check box like as shown below and click finish

Step 15 : Our models folder looks like as shown below

Step 16 :
The DummyDBEntities class is derived from DbContext class and contains DbSet<TEntity> properties of tbl_Employee type. It also overrides OnConfiguring and OnModelCreating methods. We must create an instance of DummyDBEntities to connect to the database and save or   to retrieve tbl_Employee data. 

Step 17 Our model class looks like as shown below.In database first approach this code is automatically generated by visual studio from database table.

Step 18: Connection string is auto generated in database first approach which is shown below 

Step 19 : Right click on controller folder ->Add ->Controller as shown below

Step 20 : Dialogue box will open once you click on controller and select MVC 5 controller - Empty and click Add as shown below 

Step 21 : Rename as HomeController and click Add button.Don't remove controller after Home because it is convention of MVC and MVC works on convention.

Step 22 : Now it is time to install PagedList library through Nuget package manager and for this right click on Project or Solution -> Manage Nuget Packages as shown below

Step 23 : Type PagedList in search bar and install PagedList.MVC and PagedList automatically install as shown below

Step 24 : Replace your HomeController code with following code 
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using PagedList;  
 namespace PagingInMVC.Controllers  
 {  
   public class HomeController : Controller  
   {  
     DummyDBEntities dummyDBEntities = new DummyDBEntities();  
     // GET: Home  
     public ActionResult Index(int ? page,int pageSize=2)  
     {  
       int pageNumber = page ?? 1;  
       var onePageOfEmployees = dummyDBEntities.tbl_Employee.ToList().ToPagedList(pageNumber, pageSize);  
       if(Request.IsAjaxRequest())  
       {  
         return PartialView("_EmployeeGrid", onePageOfEmployees);  
       }  
       return View(onePageOfEmployees);  
     }  
   }
 }  
Step 25 : Rebuild the project as shown below


Step 26 : Right click inside Index action and dialogue box will open and choose Add View.


Step 27 :Select List from template,model class,data context class and layout page and click on Add as shown below

Step 28: Again go to Nuget package Manager and install 
Microsoft.jQuery.Unobtrusive.Ajax as shown below


Step 29 : Go to Views->Home->Index.cshtml and replace this code 
@using PagedList
@using PagedList.Mvc
@model IPagedList<PagingInMVC.Models.tbl_Employee>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<div id="employee-grid">
    @{ 
        Html.RenderPartial("_EmployeeGrid", Model);
    };
</div>
@section scripts{
   
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    }
Step 30: Views -> Home->Right click on Home->Add->Add View->select create as partial view check box and add partial view with empty template and paste the following code 
@using PagedList
@using PagedList.Mvc
@model IPagedList<PagingInMVC.Models.tbl_Employee>
<table class="table">
    <tr>
        <th>
            Employee Name
        </th>
        <th>
            Salary
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Salary)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.EmpID }) |
                @Html.ActionLink("Details", "Details", new { id = item.EmpID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.EmpID })
            </td>
        </tr>
    }

</table>
@Html.PagedListPager(Model, page => Url.Action("Index", new { page=page}),PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() {HttpMethod="GET",UpdateTargetId= "employee-grid" }))
Step 31 : Run your project and output is shown below 



Happy Coding !!!

Categories

Angular Asp.net MVC C sharp MUM SignalR WCF
Powered by Blogger.

Tags

Angular Asp.net MVC C sharp MUM SignalR WCF

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page