ASP.NET MVC - What is MVC (Model view controller)?

Model-View-Controller () framework provides an alternative to the framework, which separates an application into three main components: the model, the view, and the controller (as shown).

What is MVC (Model view controller)

 

Figure 01: Invoking a controller action that expects a parameter value


ASP.NET MVC - What are task of each MVC components?

Model- Model objects retrieve and store model state in a database, implement the business logic for the applications.
View-Used to create user interface (UI) from model data.
Controller-handle user interaction, work with the model, and ultimately select a view to render


ASP.NET MVC - What is namespace for MVC framework?

The framework is defined in the System.Web. namespace and is a fundamental, supported part of the System.Web namespace.



ASP.NET MVC - Explain Page Life Cycle?

Page Lifecycle of an ASP.NET MVC:

  1. App initialization- Browser request pages to IIS

  2. Perform routing - IIS will pass this request to Application UrlRoutingMoule will try to find Route defined in RouteTable

  3. Create MVC request handler- UrlRoutingMoule will try to find matching Route defined in RouteTable collection. If matching route found - MvcRouteHandler will create instance of MvcHandler

  4. Controller-

    1. Create controller- MvcHandler will create an instance of controller

    2. Execute controller - MvcHandler calls the controllers Execute method

    3. Invoke action - controller determines which action method of the controller class to call, and then calls that method.

  5. Controller to Model - Controller work with Model- to retrieve and store data, to perform business logic for application.

  6. Model to Controller- Model provides data to controller

  7. Controller to View - Controller execute the result by returning a result type.

  8. View to Controller - View can also directly interact with controller (e.g. while interacting with  multiple modules ).

  9. Return Result to IIS - Appropriate return type based on action will be returned to IIS.

  10. Return to Browser - Render result to Browser


ASP.NET MVC - Can we integrate MVC with ASP.NET?

Yes, The ASP.NET framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing features, such as master pages and membership-based authentication.


ASP.NET MVC - What are features of the ASP.NET MVC Framework?

  1. Separation of application tasks -Easy to Manage - Manage complexity by dividing an application into the model, the view, and the controller

  1. Full control over the behavior of an application - as it doesn't use view state or server-based forms which will give full control to developer.

  1. Better support for test-driven development (TDD)- Easy to Test

  2. Best suited for large team

  3. An extensible and pluggable framework- You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models.  DI allows you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file.

  1. Powerful URL-mapping component- URL's are comprehensible and searchable URLs.

  1. Support for existing markup - ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files)

  1. Support for existing ASP.NET features- nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture. 


ASP.NET MVC - Explain application life cycle?

Tips for Women in the days of menstruation

Page Life cycle of an ASP.NET MVC:

  1. App initialization- Browser request pages to IIS

  2. Perform routing - IIS will pass this request to Application UrlRoutingMoule will try to find Route defined in RouteTable

  3. Create MVC request handler- UrlRoutingMoule will try to find matching Route defined in RouteTable collection. If matching route found - MvcRouteHandler will create instance of MvcHandler

  4. Controller-

    1. Create controller- MvcHandler will create an instance of controller

    2. Execute controller - MvcHandler calls the controllers Execute method

    3. Invoke action - controller determines which action method of the controller class to call, and then calls that method.

  5. Controller to Model - Controller work with Model- to retrieve and store data, to perform business logic for application.

  6. Model to Controller- Model provides data to controller

  7. Controller to View - Controller execute the result by returning a result type.

  8. View to Controller - View can also directly interact with controller (e.g. while interacting with  multiple modules ).

  9. Return Result to IIS - Appropriate return type based on action will be returned to IIS.

  10. Return to Browser -Render result to Browser

What are features of the ASP.NET MVC Framework?

  1. Separation of application tasks -Easy to Manage - Manage complexity by dividing an application into the model, the view, and the controller

  1. Full control over the behavior of an application - as it doesn't use view state or server-based forms which will give full control to developer.

  1. Better support for test-driven development (TDD)- Easy to Test

  2. Best suited for large team

  3. An extensible and pluggable framework- You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models.  DI allows you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file.

  1. Powerful URL-mapping component- URL's are comprehensible and searchable URLs.

  1. Support for existing markup - ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files)

  1. Support for existing ASP.NET features- nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture. 


ASP.NET MVC - Getting List Of All Active Sessions

Download Free Source Code Sample :List_Active_Sessions_In_ASP_NET_Web_Form_MVC.zip


Introduction

In this article we are going to see how can we can we track active users in ASP.NET (Web Form & MVC) web application, and to answer questions like How to get online users count? Track/get active user information? etc.

We are going to do it in four steps:

  1. Creating Session Repository

  2. Setting web.config Configuration

  3. Storing Session Data

  4. Removing Session Data

  5. Show Online User (Active Sessions) Count

Background

Please download sample code so that you can follow code along with documentation. Sample code is created using ASP.NET (MVC) framework using Visual studio 2013.

UsingMultipleModules_ASP_NET_MVC_1

Creating Session Repository In ASP.NET (Web Form and MVC)

Add class file ‘ActiveSessions.cs’ and add code listed below.


public static class ActiveSessions
 {
 private static List<string> _sessionInfo;
 private static readonly object padlock = new object();

 public static List<string> Sessions
 {
 get
 {
 lock (padlock)
 {
  if (_sessionInfo == null)
  {
  _sessionInfo = new List<string>();
  }
  return _sessionInfo;
 }
 }
 }

 public static int Count
 {
 get
 {
 lock (padlock)
 {
  if (_sessionInfo == null)
  {
  _sessionInfo = new List<string>();
  }
  return _sessionInfo.Count;
 }
 }
 }
 }

Setting web.config Configuration In ASP.NET (Web Form and MVC)

Set session state as “InProc’


<system.web> 
	<sessionState mode="InProc" />
</system.web>

Storing Session Data In ASP.NET (Web Form and MVC)

In Session_Start method in global.asax.cs will be adding session value to repository (ActiveSessions).


protected void Session_Start(object sender, EventArgs e)
 {
 ActiveSessions.Sessions.Add(Session.SessionID);
 }

Removing Session Data In ASP.NET (Web Form and MVC)

When users are out of website following code will be removing its entry from repository (ActiveSessions)


protected void Session_End(object sender, EventArgs e)
 {
 ActiveSessions.Sessions.Remove(Session.SessionID);
 }

Closing the browser window, or browsing to another site will NOT cause Session_End to fire, at least, not straightaway - the server has absolutely no way of knowing what happens on the client machine until it gets another HttpRequest from it. In this instance, Session_End will fire when the session times out naturally. Default Session time out is 20 minutes.

Show Online Users (Active Sessions) Count In ASP.NET (Web Form and MVC)

Now that we have session information stored in ActiveSessions object, we can show online users count as follows-

Code For MVC 4


<%=NamespaceOfActiveSessionClassFile.ActiveSessions.Count %>

Code For MVC 5


@NamespaceOfActiveSessionClassFile.ActiveSessions.Count

Please like this article on social site if this worked for you… Coding is fun !!! Isn't it... 


ASP.NET MVC - What are the benefits of using MVC?

  1. Separation of application tasks -Easy to Manage - Manage complexity by dividing an application into the model, the view, and the controller

  1. Full control over the behavior of an application - as it doesn't use view state or server-based forms which will give full control to developer.

  1. Better support for test-driven development (TDD)- Easy to Test

  2. Best suited for large team

  3. An extensible and pluggable framework- You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components. The ASP.NET MVC framework also supports the use of Dependency Injection (DI) and Inversion of Control (IOC) container models.  DI allows you to inject objects into a class, instead of relying on the class to create the object itself. IOC specifies that if an object requires another object, the first objects should get the second object from an outside source such as a configuration file.

  1. Powerful URL-mapping component- URL's are comprehensible and searchable URLs.

  1. Support for existing markup - ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files)

  1. Support for existing ASP.NET features- nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture. 


ASP.NET MVC - Working With Multiple Models In A Single View

Download Sample Source Code-Using Multiple Models In Single View ASP.NET_MVC_5.zip


Introduction

 

Most of the real work application requires to show data from multiple/different Models / Tables / Databases. Showing multiple models in a view is common requirement, that's where I started different ways to achieve this.

Best approaches of passing / using multiple models (objects) in one view in ASP.NET MVC 4 / MVC 5 are as follows:

  1. Using Combined Model (Model with multiple objects)

  2. Using Partial Views

  3. Using Ajax

  4. Data Carrier in MVC

    • ViewBag

    • ViewData

    • TempData

Background

Please download sample code so that you can follow code along with documentation.

Once you build and run code you will see -

UsingMultipleModules_ASP_NET_MVC_1

Here I have provided menu option for each approach. What you can do is as you proceed each approach run application click on corresponding menu option and review code.

Using the code

  1. Create ASP.NET MVC 4 Project

Open Visual studio and select ASP.NET MVC 4 Template

UsingMultipleModules_ASP_NET_MVC_2

  1. Select Project Template

    I am are using Intranet template with Razor view engine.

UsingMultipleModules_ASP_NET_MVC_3

  1. Setting Up Test Data  and Models

Add Author.cs and Book.cs file in Models folder

Author.cs  -
public class Author

{

public Author(int authorID, string authorString, int authorRating, List bookPublished)

{

this.AuthorID = authorID;

this.AuthorTitle = authorString;

this.AuthorRating = authorRating;

this.BookPublished = bookPublished;

}

public int AuthorID;

public string AuthorTitle;

public int AuthorRating;

public List BookPublished { get; set; }

}

Book.cs -

public class Book

{ 

public Book(int bookID, string bookString, int bookRating)

{

this.BookID = bookID;

this.BookTitle = bookString;

this.BookRating = bookRating;

}

public int BookID;

public string BookTitle;

public int BookRating;

}

 

  1. Add ‘DataSource.cs’ file to populate dummy data

 

public class DataSource

{

public List GetBooks()

{

return new List {

new Book (1, "Life of Star", 5),

new Book (2, "Game of Star", 2),

new Book (3, "TBD", 4) ,

new Book (4, "Life of Moon", 5),

new Book (5, "Game of Moon", 2),

new Book (6, "TBD", 4) 

};

}

public List GetAuthors()

{

return new List {

new Author (1, "John", 5, new List {1, 2 }) ,

new Author (2, "Tom", 5, new List {3,6}) ,

new Author (3, "Tim", 5, new List {4,5})

};

}

public List GetTop2Books()

{

return new List {

new Book (1, "Life of Star", 5),

new Book (5, "Life of Moon", 2),

};

}

}

 

  1. Make Home/Index view as follows

 

@{

ViewBag.Title = "Home Page";

}<h1>Use menu options to see how it works !!!</h1>

 

  1. Add styles for each model in Content/Site.css

 

/*Models css*/

.FirstTable {

background-color:#8ECD35;

width:200px;
}

.SecondTable {

background-color:#F4901E;

width:200px;

}

.ThirdTable {

background-color:#FFBB00;

width:200px;

}

.FirstTableDiv, .SecondTableDiv, .ThirdTableDiv, .Separator {

float:left;

}

.Separator {

 width:10px;

}

 

Using Combined Model (Model with multiple objects)

 

  1. Create Combined Model ()

public class MyViewModel

{

public List Books { get; set; }

public List Authors { get; set; }

public List TopBooks { get; set; }

}
  1. Add ‘GetAllModels’ Action in Home Controller

In code below you will notice that return type is ‘MyViewModel’ which consist of Books, Authors and Top Books.

DataSource db = new DataSource();

public ActionResult GetAllModels() {

var viewModels = new DataSource.MyViewModel

{

Books = db.GetBooks(),

Authors = db.GetAuthors(),

TopBooks = db.GetTop2Books()

};

return View(viewModels);

}
  1. Add View - Home/GetAllModels.cshtml

@model UsingMultipleModels.Models.DataSource.MyViewModel

@{
ViewBag.Title = "Using Combined Model -Get All Models From One Action";
}

<h2>@ViewBag.Title</h2>
<div>
 <div class="FirstTableDiv">
 <table class="FirstTable">
 <tr>
 <th>
 Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model.Books)
 {
 <tr>
 <td>
 @item.BookTitle
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
 </div>
 <div class="Separator"> </div>
 <div class="SecondTableDiv">
 <table class="SecondTable">
 <tr>
 <th>
 Authors<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model.Authors)
 {
 <tr>
 <td>
 @item.AuthorTitle;
 </td>
 <td>
 @item.AuthorRating
 </td>
 </tr>
 }

 </table>
 </div>
 <div class="Separator"> </div>
 <div class="ThirdTableDiv">
 <table class="ThirdTable">
 <tr>
 <th>
 Top Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model.TopBooks)
 {
 <tr>
 <td>
 @item.BookTitle;
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
 </div>
</div>
  1. Will Add Link In Site Menu Options

@Html.ActionLink("Home", "Index", "Home") 
@Html.ActionLink("Using Combined Model", "GetAllModels", "Home")

Using Partial View:

Here we are only passing main object (Model) and will create separate action methods for partial view

  1. Add Action method for partial view

public ActionResult PartialViews()

{

return View(db.GetBooks());

}
  1. Add View - Home/PartialViews.cshtml

@model IEnumerable<UsingMultipleModels.Models.Book>

 @{
 ViewBag.Title = "Using PartialViews-Independent action and views ";
 }

 <h2>Using Partial Views - Get Models From Different Action </h2>

 <div>
 <div class="FirstTableDiv">
 <table class="FirstTable">
 <tr>
 <th>
 Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model)
 {
 <tr>
 <td>
 @item.BookTitle
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
 </div>
 <div class="Separator"> </div>
 @Html.Partial("_GetAuthors")
 <div class="Separator"> </div>
 @Html.Partial("_GetTop2Books")
 </div>
  1. Add ‘GetAuthors’ and ‘GetTop2Books’ Actions In Home Controller

public ActionResult GetAuthors()

{

return View(db.GetAuthors());

}

public ActionResult GetTop2Books()

{

return View(db.GetTop2Books());

}
  1. Add Views - ‘Home/_GetAuthors.cshtml’ and ‘Home/_GetTop2Books.cshtml’

_GetAuthors.cshtml

@{
var authors = new UsingMultipleModels.Models.DataSource().GetAuthors();
}
<div class="SecondTableDiv">
 <table class="SecondTable">
 <tr>
 <th>
 Authors<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in authors)
 {
 <tr>
 <td>
 @item.AuthorTitle
 </td>
 <td>
 @item.AuthorRating
 </td>
 </tr>
 }

 </table>
</div>
 

_GetTop2Books.cshtml

@{
var topBooks = new UsingMultipleModels.Models.DataSource().GetTop2Books();
}

<div class="ThirdTableDiv">
 <table class="ThirdTable">
 <tr>
 <th>
 Top Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in topBooks)
 {
 <tr>
 <td>
 @item.BookTitle;
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
</div>
  1. Will Add Link In Site Menu Options

@Html.ActionLink("Home", "Index", "Home") 
@Html.ActionLink("Using Combined Model", "GetAllModels", "Home") 
@Html.ActionLink("Using Partial Views", "PartialViews", "Home")

Using Ajax

  1. Add ‘AjaxView’ Action In Home Controller

public ActionResult AjaxView()

{

return View(db.GetBooks());

}
  1. Add View - ‘Home/AjaxView.cshtml’

@model IEnumerable<UsingMultipleModels.Models.Book>

@{
    ViewBag.Title = "Using Ajax Views-Get Models From Different Action Independent action and views";
}

<h2>Using Ajax -Get Models From Different Action  Using Ajax </h2>

<div>
    <div class="FirstTableDiv">
        <table class="FirstTable">
            <tr>
                <th>Books<hr />
                </th>
                <th>Rating<hr />
                </th>
            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @item.BookTitle
                    </td>
                    <td>
                        @item.BookRating
                    </td>
                </tr>
            }
        </table>
    </div>
    <div class="Separator"> </div>
    <div id="Section_Authors"></div>
    <div class="Separator"> </div>
    <div id="Section_Top2Books"></div>
   
</div>

 

  1. Add Views - ‘Home/GetAuthors.cshtml’ and ‘Home/GetTop2Books.cshtml’

GetAuthors.cshtml

 
 @model IEnumerable<UsingMultipleModels.Models.Author>
 @{
 Layout = string.Empty;
 }

 <div class="SecondTableDiv">
 <table class="SecondTable">
 <tr>
 <th>
 Authors<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model)
 {
 <tr>
 <td>
 @item.AuthorTitle
 </td>
 <td>
 @item.AuthorRating
 </td>
 </tr>
 }

 </table>
 </div>
 

GetTop2Books.cshtml

@model IEnumerable<usingmultiplemodels.models.book>
@{
 Layout = string.Empty;
}

<div class="ThirdTableDiv">
 <table class="ThirdTable">
 <tr>
 <th>
 Top Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model)
 {
 <tr>
 <td>
 @item.BookTitle;
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
</div>
  1. Will Add Link In Site Menu Options

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Using Combined Model", "GetAllModels", "Home")

@Html.ActionLink("Using Partial Views", "PartialViews", "Home")

@Html.ActionLink("Using Ajax-Multiple", "AjaxView", "Home")

Using Data Carrier in MVC

Which data carrier you should be using based on its features. In this approach you will assign different Model object to data carrier (ViewBag/ViewData/TempData) and access it from view.

  1. ViewBag

    It is most popular data carrier in MVC because ViewBag is dynamic property and doesn't requires typecasting.

  2. ViewData

    It is dictionary object derived from ViewDataDictionary class, requires typecasting for complex data type and need check for null values for to avoid errors.

  3. TempData

    It is dictionary object derived from TempDataDictionary class, data is stored in short lives session.


Download Sample Source Code-Using_Multiple_Models.zip


Please like this article on social site if this worked for you… Coding is fun !!! Isn't it... 


ASP.NET MVC - What are partial views in MVC?

In web form we use create and use reusable component e.g web user control or a web server control. Similarly in MVC we will use Partial view.

Partial views can be placed in Views folder and each view folder for Controller as shown below.

ASP.NET MVC Partial View

Characteristics of is Partial view:

It’s a view who do not have layout defined,  starts with '_' , can be placed in shared views folder.

Where / When to Partial views can be used?

  • Need to reuse same view at multiple places (e.g. Header, Footer, Left panel)
  • Need to use multiple / Related models in Main view (e.g. Get Products additional Info )

Syntax of using Partial view :

Html.RenderPartial("~/Views/Shared/_Header.cshtml");

Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);

OR

@Html.Partial("~/Views/Shared/_Header.cshtml");

@Html.Partial("~/Views/Shared/_Product.cshtml", product);


ASP.NET MVC - How Routing Works?

How Request is handled in ASP.NET MVC:

Tips for Women in the days of menstruation

 

Is ten step process, as follows:

  1. App initialization- Browser request pages to IIS

  2. Perform routing - IIS will pass this request to Application UrlRoutingMoule will try to find Route defined in RouteTable

  3. Create MVC request handler- UrlRoutingMoule will try to find matching Route defined in RouteTable collection. If matching route found - MvcRouteHandler will create instance of MvcHandler

  4. Controller-

    1. Create controller- MvcHandler will create an instance of controller

    2. Execute controller - MvcHandler calls the controllers Execute method

    3. Invoke action - controller determines which action method of the controller class to call, and then calls that method.

  5. Controller to Model - Controller work with Model- to retrieve and store data, to perform business logic for application.

  6. Model to Controller- Model provides data to controller

  7. Controller to View - Controller execute the result by returning a result type.

  8. View to Controller - View can also directly interact with controller (e.g. while interacting with  multiple modules ).

  9. Return Result to IIS - Appropriate return type based on action will be returned to IIS.

  10. Return to Browser - Render result to Browser


ASP.NET MVC - What is difference between Dynamic vs Strongly Typed Views?

There are three ways to pass information from a controller to a view in ASP.NET MVC 3 and above:

  1. As a strongly typed model object.

@model IEnumarable<<MVCAppNamespace>.Controller.<ModelName>>

@foreach (var item in Model) { 

}

  1. As a dynamic type (using @model dynamic)

@model dynamic

@foreach (var item in Model) { 

}

  1. Using the ViewBag

@foreach (var item in ViewBag.<<ModelName>>) { 

}

  


ASP.NET MVC - Difference between TempData[] and ViewData[]

In ASP.NET MVC - these are almost same but purpose is different.
TempData[] can persist for two request whereas ViewData[] only for one request.

Normaly TempData[] is used when we are passing some info from one request to other. like in case of exception we wanted to get exception instance on error page. so in this case we can keep exception instance in TempData[].

Please find mire on reference links.
 


ASP.NET MVC - Routing From Controller Based On Access or Business Logic

Less first understand rounting module in MVC as shown below diagram-


 

For more information on MVC Routing  refer -ASP.NET MVC Routing

Consider this situation where if logged in user has admin right then you want to redirect him to Admin if user is not admin redirect to Listing (index)page.


Here is code snippet to do this:



        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(ITEM item)
        {
            if (ModelState.IsValid)
            {
                db.Entry(item).State = EntityState.Modified;
                db.SaveChanges();
                if (User.IsInRole("Admin"))
                {
                    return RedirectToAction("Admin");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
            return View(item);
        }

ASP.NET MVC - Adding and Updating Meta Tags Dynamically

 

If you are working in ASP.NET MVC have questions like -
How to pass page's meta tags - adding Meta tags on Razor engine .cshtml Pages/adding it dynamically ?
Here is answer-

In this article we are going to see three ways of doing this-

 

 

  1. Using JQuery

  2. Using ViewBag

  3. Using @RenderSection and @Section

HTML_MetaTags_1

 

Approach 1 - Using Jquery :

 

A) In the "_Layout.cshtml" page add a new section call inside the <head> tag, as given below:

<head> 
 	<meta name="keywords" content="" />
 	<meta name="description" content="" />
</head>
B) In Page/View ( e.g Index )add following Script :
<script>
    $('meta[name=description]').attr('content', 'yourDescription');
    $('meta[name=keywords]').attr('content', 'yourKeyword');
</script>
 

 

Approach 2 - Using ViewBag:

 

A) In the "_Layout.cshtml" page add a new section call inside the <head> tag, as given below:
<head>
<meta name="description" property="og:description" content="@ViewBag.PageDescription" />
<meta name="keywords" property="keywords" content="@ViewBag.PageKeywords"/>
<head/>

 

 B) In Page/View ( e.g Index )add following section/code:

 

@{
////DESCRIPTION_VALUE and KEYWORD_VALUE - Can be replaced with model values  ViewBag.PageTitle = 'DESCRIPTION_VALUE';       //Model.Title;  ViewBag.PageKeywords ='KEYWORD_VALUE';  //Model.Keywords;
}

 

Approach 3 - Using @RenderSection and @Secton :

 

A) Declare meta tags in head section of "_Layout.cshtml" page as shown below
<head>
@RenderSection("META", required: false);
<head/>
B) In Page/View (e.g. Index) add following Section/Code
@Secton META{
@*///DESCRIPTION_VALUE and KEYWORD_VALUE - Can be replaced with model values (e.g. @Model.PageDescription) or ViewBag (e.g.@ViewBag.PageDescription)*@
<meta name="description" property="og:description" content="DESCRIPTION_VALUE" />
<meta name="keywords" property="keywords" content="KEYWORD_VALUE" />
}

Please like this article on social site if this worked for you… Coding is fun !!! Isn't it... 


ASP.NET MVC - Exception Handling In Web Application

Exception Handling in ASP.NET MVC Web Application

 

ASP.NET MVC Error handling using CSharp:

Exception handling is crucial part of every application. It is required for logging errors into database or text/log file, very importantly presenting them to the user in a nicely in case of exception.

Introduction:

When I was working on application I encounter exceptions (e.g. 400, 500, etc ) but I was not sure of what might have caused it. That's where I started exploring various approaches of exception handling in ASP.NET MVC.

There are various ways to handle exceptions, based upon usability and error location/type (SQL, Application, etc)

We are going to see all of them -I will keep on adding stuff to this article :)

It seems then, that this is a good exercise in understanding a number of things:

 

Exception Handling in ASP.NET MVC - At Page/View Level - Using Action Method

 

 

Exception Handling in ASP.NET MVC - At Application Level - Using Global.aspx

 

Using Code/ How It Works:

Exception Handling in ASP.NET MVC - At Page/View Level - Using Action Method

 

This typical way of handling exceptions, using try...catch block inside action method as follows -

 
 public ActionResult Index() {
 try {
 //To do - code block processing
 } catch (Exception e) {
 //Redirect to an error page
 Response.Redirect("URL to the error page");
 }
 return View();
 }
 

When return type of action is JSON you should return a JSON with the exception message and handle it on the client side, as follows-

 
 public JsonResult GetJson() {
 try {
 //To do - code block processing
 } catch (Exception e) {
 //Return the exception message as JSON
 return Json(new {
 error = e.Message
 });
 }
 return Json("Return data here");
 }
 
  • Advantage - custom error handling can be done for particular action method.

  • Disadvantage- We need to repeat code (try… catch block) in every action (for each view/page).

 

 

Exception Handling in ASP.NET MVC - At Application Level - Using Global.aspx

 

 

In previous approach we need to repeat code, that's why it is good to handle exceptions at application level, so that will write code once use it for all pages.

In order to do that you have to add Application_Error() function definition in Global.aspx as follows, this is just an example.

 
 protected void Application_Error() {
 Exception unhandledException = Server.GetLastError();
 int httpCode = 0;
 // Handle HTTP errors
 if (unhandledException.GetType() == typeof (HttpException)) {
 HttpException httpException = unhandledExceptionas HttpException;
 if (httpException == null) {
 Exception innerException = unhandledException.InnerException;
 httpException = innerException as HttpException;
 }
 if (httpException != null) {
 httpCode = httpException.GetHttpCode();
 switch (httpCode) {
 case (int) HttpStatusCode.Unauthorized:
 Response.Redirect("~/Error/ErrorUnauthorized");
 break;
 case 404:
 Response.Redirect("~/Error/ErrorNotFound");
 break;
 default:
 Response.Redirect("~/Error/Default");
 break;
 }
 }
 }
 // Log the exception and notify system operators
 // You can create Class file e.g. Exception utility to log error details either in database or text file
 //ExceptionUtility.LogException(unhandledException, Request.Url.ToString(), httpCode);
 // Clear the error from the server
 Server.ClearError();
 }

 

 

Thank You...Please like this article on social site if this worked for you… Coding is fun !!! Isn't it...

ASP.NET MVC - Asynchronous Call Using Controller Action Method


Download Sample Source Code-MVC Asynchronous Demo_ASP_NET_MVC CSharp


Introduction

In real-time scenarios we always want to accomplish something differently, effectively and efficiently. Using multiple models in single view is common requirement in most of application. I always prefer to use asynchronous methods for better performance.

Background

Here we are going to accomplish UI as shown below, consist of two modes rendered.

  AsynchronousRequest-ActionUsingJQuery-JavaScriptASPNETMVC

Using code

  1. Create ASP.NET MVC  Project

Open Visual studio and select ASP.NET MVC 4 Template

UsingMultipleModules_ASP_NET_MVC_2

  1. Select Project Template

    - I am are using Intranet template with Razor view engine.

UsingMultipleModules_ASP_NET_MVC_3

  1. Setting Up Test Data  and Models

Add Author.cs and Book.cs file in Models folder-

Author.cs:

public class Author
 {
 public Author(int authorID, string authorString, int authorRating, List bookPublished)
 {
  this.AuthorID = authorID;
  this.AuthorTitle = authorString;
  this.AuthorRating = authorRating;
  this.BookPublished = bookPublished;
 }

 [Key]
 [Required]
 public int AuthorID;
 public string AuthorTitle;
 public int AuthorRating;
 public List BookPublished { get; set; }
 }

Book.cs:

public class Book
 { 
 public Book(int bookID, string bookString, int bookRating)
 {
  this.BookID = bookID;
  this.BookTitle = bookString;
  this.BookRating = bookRating;
 }

 [Key]
 [Required]
 public int BookID;
  
 public string BookTitle;
 public int BookRating;
 }

Add datasource:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace MVCAsynchronousDemo.Models
{
 public class DataSource
 {
 public List<Book> GetBooks()
 {
  return new List<Book> { 
  new Book (1, "Life of Star", 5), 
  new Book (2, "Game of Star", 2),
  new Book (3, "TBD", 4) , 
  new Book (4, "Life of Moon", 5), 
  new Book (5, "Game of Moon", 2),
  new Book (6, "TBD", 4) 
  };
 }

 public async Task<List<Book>> GetBooksAsync()
 {
  return new List<Book> { 
  new Book (1, "Life of Star", 5), 
  new Book (2, "Game of Star", 2),
  new Book (3, "TBD", 4) , 
  new Book (4, "Life of Moon", 5), 
  new Book (5, "Game of Moon", 2),
  new Book (6, "TBD", 4) 
  };
 }

 public List<Author> GetAuthors()
 {
  return new List<Author> { 
  new Author (1, "John", 5, new List<int> {1, 2 }) ,
  new Author (2, "Tom", 5, new List<int> {3,6}) ,
  new Author (3, "Tim", 5, new List<int> {4,5}) 
  };
 }

 public List<Book> GetTop2Books()
 {
  return new List<Book> { 
  new Book (1, "Life of Star", 5), 
  new Book (5, "Life of Moon", 2),
  };
 }

 public class MyViewModel
 {
  public List<Book> Books { get; set; }
  public List<Author> Authors { get; set; }
  public List<Book> TopBooks { get; set; }
 }
 }
}
  1. Create Action method

Add BookListAsync Action method in Home controller as shown-

public async Task<List<Book>> BooksListAsync()
 {
  List data = await db.GetBooksAsync();
  return data;
 }
  1. Add placeholder to render data in view (e.g. index.cshtml)

add placeholder i.e. Partial view -"BooksListAsync", as shown below

 

<div class="row">@Html.Partial("BooksListAsync")</div>

 

  1. Add definition of partial view BooksListAsync.cshtml, as below-

 


@using MVCAsynchronousDemo.Controllers;

@{
 Layout = string.Empty;
 var bookList = new HomeController().BooksListAsync();
}

<table class="table">
 <tr>
 <th>Book ID</th>
 <th>Book Title</th>
 </tr>

 @foreach (var item in bookList.Result)
 {
 <tr>
  <td>
  @item.BookID
  </td>
  <td>
  @item.BookTitle
  </td>
 </tr>
 }

</table>


Summary

Is it simple approach for working with multiple models and creating dynamic user interface?


Download Sample Source Code-MVC Asynchronous Demo_ASP_NET_MVC CSharp


Thank you …Please like this article on social site if this worked for you… Coding is fun !!! Isn't it...

ASP.NET MVC - Uploading, Downloading & Streaming Files

 

Download Sample Source Code - Working With Files ASP.NET MVC 5


File processing- ( Working with Uploading / Downloading / Streaming Files ) using CSharp in ASP.NET MVC, we are going to cover following :

Setting up form method and content type

File Upload

File Download

File Streaming

 

File Streaming

 

Setting up form method and content type:

 

In Web Forms, when you drag a FileUpload control on to the designer, html form that wraps the entire page is decorated with an extra attribute: enctype="multipart/form-data" and method=”post”.

  • method=”post” - is needed because the form by default will be submitted via the HTTP get method.

  • enctype="multipart/form-data" - is needed to post form in multiple parts.

The FileUpload itself is rendered as an html input type=file. Within an MVC View, there are a number of ways to set this up. The first is with HTML:

<form action="/Home/UploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="FileUpload" /><br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
</form> 

In ASP.NET MVC this can be done using using the Html.BeginForm() extension method  as follows :

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype="multipart/form-data"})){ 
<input type="file" name="FileUpload" /><br />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
} 

 

File Upload

Uploading File On Server :

We have seen how to post files (ASP.NET MVC Working With Files - Setting up form method and content type-Post File ), files will be available in post method defined in controller. Using Request.Files and HttpPostedFile we are going to upload using following code.

This is generic code, will work with uploading multiple files (if multiple files are posted)


public class HomeController : Controller
{ 

[HttpPost]
public ActionResult UploadFile()
{  
foreach (int i;i< Request.Files.Count; i++)

{

HttpPostedFileBase hpf = Request.Files[file];

if (hpf.ContentLength == 0)

continue;

// You have to make sure ‘File Uploads’ directory exists

string savedFileName = Path.Combine(

AppDomain.CurrentDomain.BaseDirectory+ "FileUploads/",

Path.GetFileName(hpf.FileName));

  hpf.SaveAs(savedFileName);

}

return View();
}
}

 

Uploading Multiple Files On Server:

Now that we have see how to post file and how to upload file on server.

  1. ASP.NET MVC Working With Files - Setting up form method and content type (Post Files)

  2. ASP.NET MVC Working With Files - Uploading File On Server

In order to upload multiple file you just need to add input control (type="file") in view.

View -
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype="multipart/form-data"})){ 

<input type="file" name="FileUpload1" multiple/><br />

    <input type="submit" name="Submit" id="Submit" value="Upload" />
}

 

OR

(If you have specific number of files to upload you can define as follows - (max upload as 5 files))

@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype="multipart/form-data"})){
<input type="file" name="FileUpload1" /><br />
<input type="file" name="FileUpload2" /><br />
<input type="file" name="FileUpload3" /><br />
<input type="file" name="FileUpload4" /><br />
<input type="file" name="FileUpload5" /><br />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
} 
Post Method-

public class HomeController : Controller
{ 

[HttpPost]
public ActionResult UploadFile()
{  
foreach (int i;i< Request.Files.Count; i++)

{

HttpPostedFileBase hpf = Request.Files[file];

if (hpf.ContentLength == 0)

continue;

// You have to make sure ‘FileUploads’ directory exists

string savedFileName = Path.Combine(

AppDomain.CurrentDomain.BaseDirectory+ "FileUploads/",

Path.GetFileName(hpf.FileName));

  hpf.SaveAs(savedFileName);

}

return View();
}
}

File Download

public FilePathResult DownloadFile(string fileNameWithExtention)
{
 string path = AppDomain.CurrentDomain.BaseDirectory + "FileUploads/";
 string fileName = fileNameWithExtention;
 return File(path + fileName, "text/plain", "test.txt");
}

 

File Streaming

 


public FileStreamResult StreamFile(string fileNameWithExtention)
{
  string path = AppDomain.CurrentDomain.BaseDirectory + "FileUploads/";
  string fileName = fileNameWithExtention;
  return File(new FileStream(path + fileName, FileMode.Open), "text/plain", fileName);
}

 

 

File Download

 

 


Download Sample Source Code - Working With Files ASP_NET MVC 5


Please like this article on social site if this worked for you… Coding is fun !!! Isn't it...


ASP.NET MVC - Difference between Html.Partial vs Html.RenderPartial

 

  Html.Partial Html.RenderPartial
Razor syntax: @Html.Partial("ViewName"); @Html.RenderPartial("ViewName");
Returns: Returns MvcHtmlString Returns void
Renders: Returns a html encoded string that gets constructed inline with the parent. Directly render/write on output stream.
Speed: Slower than Html.RenderPartial Faster than Html.Partial

 


ASP.NET MVC - Types of Action Filters

Types of Filters in ASP.NET MVC:

  • Action Filters − Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.

    • ASP.NET MVC provides the following action filters −

      • Output Cache − This action filter caches the output of a controller action for a specified amount of time.

        • [OutputCache(Duration = 10)]
      • Handle Error − This action filter handles errors raised when a controller action executes.

        • [HandleError] 
      • Authorize − This action filter enables you to restrict access to a particular user or role.

        • [Authorize]
  • Authorization Filters − Authorization filters are used to implement authentication and authorization for controller actions.

    • [Authorize]
  • Result Filters − Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.

  • Exception Filters − Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.