European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Understanding Routing Precedence In ASP.NET MVC And Web API

clock August 3, 2023 09:40 by author Peter

Routing can be a very tricky issue within ASP.NET MVC and Web API applications. This can be especially true if you have a variety of different routes with varying parameters, defined in such a way that a single request could satisfy multiple routes.


This blog post will cover some of the precedence rules that are applied to routing in ASP.NET MVC and Web API and how to leverage these to ensure that the route you want to use gets used.

What are Routes? How do they work?
A Route in ASP.NET simply consists of a pattern that is going to be mapped to a handler. The handlers themselves can be a variety of different mechanisms (e.g. a physical file, a Web Forms page, or an MVC Controller class). In simplest terms, Routes define how requests are handled within your application.

Routes consist of the following three components,

    A name to identify the Route itself.
    A pattern to match URLs to match a request with its appropriate handler.
    A handler to tell requests that match the pattern where to go.

You can see an example of a route declaration in ASP.NET MVC below, which contains all three of these criteria.
    routes.MapRoute(   
    "Default", // Name  
    "{controller}/{action}/{id}", // Pattern  
    new { controller = "Home", action = "Index", id = "" } // Handler  
    );  


Routes can also be defined by using the [Route] attribute and decorating a particular Controller Action with it.
    [Route("widgets/{brand}", Order = 1)]  
    public IEnumerable<Widget> GetWidgetsByBrand(string brand) { ... }   

Since the focus of this post isn't really about routing itself and more of routing precedence, I won't go into too many more details about declaring them.

ASP.NET will store all of the defined Routes within a Routes Table and when a request comes to it, it will look through these Routes to determine the one best suited in order to serve the request. To know how this works, we need to know how Routes are prioritized and that's why this blog post exists at all.

Routes match requests using a pattern and tell them where to go.

Routing Precedence

Routing can be a blessing and a curse within an application. It can provide you with the freedom to define all sorts of very creative and easily understandable approaches to accessing the data, but when overused, things can get hairy. The primary reason that routing can make you want to pull your hair out is that a single request can match multiple routes.

The routing order can be broken down into the following steps.
    Check the Order property (if available).
    Order all Routes without an explicit Order attribute, as follows.

        Literal segments.
        Route parameters with constraints.
        Route parameters without constraints.
        Wildcard parameter segments with constraints.
        Wildcard parameter segments without constraints.

    As a tie-breaker, order the Routes via a case-insensitive string comparison.

Confused yet? That's okay
Let's talk about defining Route Order and the different types of routes for a moment, to clear things up.

Route Order

You can use the [Route] attribute to explicitly set when a particular route is going to be checked against the order property. By default, all defined routes have an order value of 0 and routes are processed from lowest to highest. This is the primary reason that it is so important for establishing the route precedence, as it's a single attribute that will govern the order in which routes are processed.

Let's look at the following three routes.
    [Route("Alpha", Order = 1)]  
    public void Fizz() { ... }   
    [Route("Beta")]  
    public void Buzz() { ... }   
    [Route("Gamma")]  
    public void FizzBuzz() { ... }   


Since the Alpha Route has an order property of 1, it will always be evaluated last. The only scenario where that would not be true would be if another route had a higher order value or an equal one (and it received priority via the other criteria).

Literal Segments
A Literal Segment Route can be thought of as a "hard-coded" route. It contains no types of parameters and no constraints. A few examples of these types of routes might look like.
    /widgets/broken  
    /employees  

Route Parameters
Route Parameters are going to have a bit more information that literals, but not by much. The only major difference is that they will have a "placeholder" that can be used to define parameters, similar to the String.Format() method.
    /widgets/{widgetId}  
    /reports/{year}/{month}  


Route Parameters with Constraints
Route Parameters can also be constrained to a specific type. This is important as they will be evaluated prior to unconstrained ones.
    /widgets/{widgetId:int}  
    /reports/{year:int}/{month:int}  

Wildcard Parameters
Wildcard Parameters are the last type of parameters to review, and you generally won't see these as much as the aforementioned types. These function as "catch-all" parameters and may contain more than a single segment.

Consider the following route,
    /query/widgets/{*queryvalues}  

Notice the {*queryvalues} segment. The leading asterisk indicates that this is a wildcard parameter and thus, it can accept all sorts of additional segments in it.
    /query/widgets/broken  
    /query/widgets/byyear/2015  

Wildcard Parameters with Constraints
Wildcard parameters can also feature type constraints just like normal route parameters as well if you are expecting a certain type,
    /query/widgets/{*byyear:int}  

Applying Precedence in Action
Now, to break this down, let's define several actions that meet the criteria of at least one of each of these routes. We will look at each phase as we order the routes.
    [RoutePrefix("widgets")]  
    public class WidgetsController: ApiController {  
            [Route("{widgetId:int}")] // Constrained Route Parameter  
            public HttpResponseMessage Get(int widgetId) {...  
                }  
                [Route("new")] // Literal Segment  
            public HttpResponseMessage GetNew() {...  
                }  
                [Route("{*features})] // Unconstrained Wildcard Parameter  
                        public HttpResponseMessage GetByFeatures(string features) {...  
                        }  
                        [Route("broken", RouteOrder = 1)] // Literal Segment (with Route Order)  
                        public HttpResponseMessage GetBroken() {...  
                        }  
                        [Route("{brand}")] // Unconstrained Route Parameter  
                        public HttpResponseMessage GetByBrand(string brand) {...  
                        }  
                        [Route("{*date:datetime}")] // Constrained Wildcard Parameter  
                        public HttpResponseMessage GetByManufacturedDate(DateTime date) {...  
                        }  
                    }  

So, with all of these routes defined, let's output all of them as they appear in the Controller and update them as we apply each rule.
    Get(int widgetId) { ... } // widgets/{widgetId:int}   
    GetNew() // widgets/new   
    GetByFeatures(string features) // widgets/{*features}   
    GetBroken() // widgets/broken   
    GetByBrand(string brand) // widgets/{brand}   
    GetByManufacturedDate(DateTime date) // widgets/{*date:datetime}   


Firstly, check the routes for the Order attribute. Now, since the GetBroken()action has an Order of 1, we know that this will be the last route to be evaluated (since the default is 0 and routes are processed in ascending order).
    Get(int widgetId) { ... } // widgets/{widgetId:int}   
    GetNew() // widgets/new   
    GetByFeatures(string features) // widgets/{*features}   
    GetByBrand(string brand) // widgets/{brand}   
    GetByManufacturedDate(DateTime date) // widgets/{*date:datetime}   
    GetBroken() // widgets/broken   


Next up, we will check for any literal routes and ensure that they will be the first to be processed. In this case, the GetNew() action meets that requirement, so move it to the beginning,
    GetNew() // widgets/new   
    Get(int widgetId) { ... } // widgets/{widgetId:int}   
    GetByFeatures(string features) // widgets/{*features}   
    GetByBrand(string brand) // widgets/{brand}   
    GetByManufacturedDate(DateTime date) // widgets/{*date:datetime}   
    GetBroken() // widgets/broken   


After literals, the next routes to be processed are constrained route parameters. The Get(int) action meets this requirement as it accepts an integer for its widgetId parameter, so it will fall next in line,
    GetNew() // widgets/new   
    Get(int widgetId) { ... } // widgets/{widgetId:int}   
    GetByFeatures(string features) // widgets/{*features}   
    GetByBrand(string brand) // widgets/{brand}   
    GetByManufacturedDate(DateTime date) // widgets/{*date:datetime}   
    GetBroken() // widgets/broken   


Next, unconstrained route parameters are processed. The GetByBrand(string)action meets this requirement as it contains a parameter, but it doesn't specify a type for it,
    GetNew() // widgets/new   
    Get(int widgetId) { ... } // widgets/{widgetId:int}   
    GetByBrand(string brand) // widgets/{brand}   
    GetByFeatures(string features) // widgets/{*features}   
    GetByManufacturedDate(DateTime date) // widgets/{*date:datetime}   
    GetBroken() // widgets/broken   


After all of the literals and route parameters have been routed, the next to be evaluated are the wildcard parameters. More specifically, the constrained wildcard parameters, which the GetbyManufacturedDate(DateTime) route matches,
    GetNew() // widgets/new   
    Get(int widgetId) { ... } // widgets/{widgetId:int}   
    GetByBrand(string brand) // widgets/{brand}   
    GetByManufacturedDate(DateTime date) // widgets/{*date:datetime}   
    GetByFeatures(string features) // widgets/{*features}   
    GetBroken() // widgets/broken   

And finally, the last route type to evaluate is unconstrained wildcard parameters (or "catch-all" routes). The GetByFeatures(string) route fits under that category so it will be placed prior to the GetBroken() route, which had a higher Order property,
    GetNew() // widgets/new   
    Get(int widgetId) { ... } // widgets/{widgetId:int}   
    GetByBrand(string brand) // widgets/{brand}   
    GetByManufacturedDate(DateTime date) // widgets/{*date:datetime}   
    GetByFeatures(string features) // widgets/{*features}   
    GetBroken() // widgets/broken   


And that's it as we don't have any ties to break. But, if a tie between two routes did exist, then a case-insensitive comparison of the route template names would resolve it.

Any requests that come through will be evaluated in that order (i.e. the first pattern to match against the URL will be action that handles the request).

Your Mileage May Vary
One important thing to point out in a post like this is that generally, you shouldn't have to deal with routing precedence too often. If you are responsible for building and designing your API, then try to keep your API as simple as possible.

Don't try to create this sprawling, verbose API of endless routes unless you absolutely have to. Complicated APIs can lead to complicated problems, and in most cases, if your API is too difficult to interact with, others won't likely want to use it (especially, if you are building a public-facing API).



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Add Identity-Based Authentication To An ASP.NET Core 6 MVC Project?

clock July 12, 2023 07:04 by author Peter

Integrating security into your application is a crucial step. So that only authenticated users are permitted access to the application. ASP.NET Core Identity is a robust system that facilitates the authentication of users in ASP.NET Core applications. User registration, login, password administration, role-based authorization, and integration with external authentication providers are among its many features.


You will learn how to add identity service to your ASP.NET 6 MVC project in this article. Before beginning, let's examine the fundamentals.

What is ASP.NET MVC Core?

Microsoft ASP.NET Core MVC is a robust and adaptable web application development framework for the ASP.NET Core platform. The model, the view, and the controller are the three distinct application components that are separated by MVC. The model represents the data and business logic of the application. It contains the necessary data structures, logic, and algorithms for manipulating and processing the data. The view is accountable for displaying the user interface to the end user. The view receives data from the model and displays it in an approachable manner. The controller mediates between the model and view. The controller manages the application's flow by receiving and processing requests and returning the appropriate response.


What is the difference between authentication and authorization?
Authentication and authorization are essential application development components. Authentication is the process of confirming a user's identity, assuring that they are who they claim to be. Authorization, on the other hand, is the process of granting or denying access to specific resources or functionalities based on the permissions and roles of the authenticated user.

It is essential to employ a secure authentication and authorization mechanism in today's digital environment, where sensitive user data and confidential information are involved. It protects user accounts, restricts unauthorised access to sensitive data, and ensures that only authorised users are able to perform specific actions within the application. By effectively incorporating authentication and authorization, developers can increase the overall security and credibility of web applications.

What is ASP.NET Identity Core?

ASP.NET Core Identity is a membership system for ASP.NET Core applications that provides support for user authentication and authorization. It simplifies the management of user accounts, passwords, and roles, allowing developers to concentrate on the essential functionality of applications.

In other words, ASP.NET provides the necessary functionality for adding features such as registering, logging in, logging out, managing users, passwords, profiles, authorization, roles, claims, tokens, and email confirmation.

ASP.NET Core Identity provides a comprehensive set of features, including user registration, login, password management, role-based authorization, and integration with external authentication providers. It integrates seamlessly with ASP.NET Core MVC, making it simple to add authentication and authorization features to your web application.

Using ASP.NET Core Identity, developers can employ secure authentication mechanisms, such as cookies and JSON Web Tokens (JWT). In addition, it features a flexible and extensible architecture that permits customization and integration with existing user repositories and providers. Whether you are developing a small-scale application or a large enterprise-level system, ASP.NET Core Identity provides the tools and APIs required to implement secure and scalable authentication and authorization solutions.

How Do I Configure ASP.NET Core Identity In My Project?
To perform authentication using Identity, I will create a brand-new project. Let us now establish the project.

1. Establishing the undertaking
Open Visual Studio 2022. Select "Create a new project" and then select "Next". Click "Next" after selecting the "ASP.NET Core Web App (Model-View-Controller)" template.


Click "Next" after customising the project and solution names and selecting the location where you desire to save the project. The name of our initiative is CRMApp.

Click "Create" after selecting "NET 6" as the framework.

Now, the project has been effectively created.

Step 2: Configuring the database
Launch SSMS (SQL Server Management Server) and use it to create and manage databases.

create database SalesCRM;
use SalesCRM;


Step 3. Open appsetting.js and set the connection string.
"ConnectionStrings":
{
  "SalesCRMcnn": "Server=***;Database=SalesCRM;User Id=**;Password=****;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}

Step 4. Creating Models
Click on Models and add a new class named SalesleadEntity.cs. In this class, add the required properties for the model as shown below.
namespace CRMApp.Models
{
    public class SalesLeadEntity
    {
        public int Id { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? Mobile { get; set; }
        public string? Email { get; set; }
        public string? Source { get; set; }
    }
}

Step 5. Adding Required Packages
Now, Right click on the project and select "Manage NuGet Packages". In the browse section, search the following packages and install them.
    Microsoft.EntityFrameworkCore
    Microsoft.EntityFrameworkCore.SqlServer
    Microsoft.EntityFrameworkCore.Tools
    Microsoft.AspNetCore.Identity.EntityFrameworkCore


Now, Create a new folder named "Data" in the project and add a new class named "ApplicationDbContext.cs".
using CRMApp.Models;
using Microsoft.EntityFrameworkCore;
namespace CRMApp.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {
        }
        public DbSet<SalesLeadEntity> SalesLead { get; set; }
    }
}

Now, open program.cs, and add the following service in the file.
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("SalesCRMcnn")));

Step 6. Adding the migration to the database
To add migration to the database, Go to "Tools" -> "NuGet Package Manager" -> "Package Manager Console", and the package manager console will open.

In the console, run the following commands.
add-migration "Initial migration"
Update-database


After running the above commands, a migration file will be added to your project, having folder name Migrations, and the database will be updated.

Step 7. Adding Controller
Click on Controller and add a new Scaffolded Item and select "MVC Controller with views, using Entity Framework," and click on "Add". A popup will open like this.

Choose "SalesLeadEntity" as the model class and "ApplicationDbContext" as DbContext class. Also, name the controller "LeadsController". Click on "Add", and a new controller will get created with action methods in it.

Now, go to "_Layout.cshtml" and add the following lines to make a new menu for the Sales Lead.
<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Leads" asp-action="Index">Sales Lead</a>
</li>


Now, if you will run the project and open the index page, you will have an empty page like this.

Here, click "Create New" to create a new record.

Once you add the records on the index page, you will have that records.

Step 8. Securing the project using Identity


Before adding Identity to the project, update the "ApplicationDbContext.cs" with the below code, as now we will be inheriting IdentityDbContext instead of DbContext.
using CRMApp.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace CRMApp.Data
{
    public class ApplicationDbContext : IdentityDbContext
    {
        ...
    }
}

Now, Right Click on the project and click on "Add new Scaffolded Item". Click on "Identity" and then click "Add".

Here, I have selected all options, but you can select according to your need and project requirements. Choose DbContextClass as "ApplicationDbContext" and Click on "Add".
Now, you will have Identity added to your project using scaffolding. Now, you will see a folder named Areas which has a sub-folder named Identity which contains a sub-folder names Account which has endpoints for login register, logout, etc in the form of razor pages.

Step 9.  Adding necessary code and updating the database

Open "_Layout.cs", and add the following code in the <nav> section before the </nav>
<partial name="_LoginPartial"/>

Now, you should be able to see Login and Register options in the right-side menu when running the project.

Add the following line in the Program.cs.
app.MapRazorPages();

Now, you will have to add migration to the database; go to "Tools", click on "NuGet Package Manager" and then on "Package Manager Console", the package manager console will open.

In the console, run the following commands.
add-migration "Identity tables migration"
Update-database

Here, a new migration file will be added to the Migration folder, and necessary tables are added to the database.

Step 10. Create a new account

Run the project and click on register to register users. A Register page will open like the one below.

Here, you can register users by filling in the fields given.

But, if you click on Sales Lead, you will see you can still access the sales lead page without logging. So, to prevent this, follow the next step.

Step 11. Adding security

Go to "LeadsController.cs"  and add attribute [Authorize] at the controller level.
namespace CRMApp.Controllers
{
    [Authorize]
    public class LeadsController : Controller
    {
       ...
    }
}


Now, if you will open the application and click on Sales Lead, you will see that you cannot access the page without logging in yourself. A page for login will open for you, as shown below.

Once you log in yourself using the email and password. You will be able to access the Index page with Sales Lead Details. Also, you will have options to edit, get details and delete the records.

Here, you can see the details.


As you have seen, we have successfully added authentication to our ASP. NET 6 projects using the Identity Service.

Conclusion

ASP.NET Core Identity is a powerful tool for implementing user authentication and authorization in ASP.NET Core applications. By leveraging its features, developers can easily incorporate secure and scalable authentication mechanisms into their web applications, enhancing overall security and user trust. ASP.NET Core Identity simplifies the process of managing user accounts, passwords, and roles, allowing developers to focus on the core functionality of their applications. With its seamless integration with ASP.NET Core MVC, developers can create robust user management functionality and ensure that only authorized users can access specific resources or functionalities within the application.

By following the steps outlined in this article, developers can successfully set up ASP.NET Core Identity in their projects and enjoy the benefits of a secure and efficient authentication system.



ASP.NET MVC 6 Hosting - HostForLIFE :: How to Redirect the Desired Web Page in ASP.Net Core MVC?

clock July 3, 2023 10:10 by author Peter

ASP.NET Core MVC is a framework used to develop web applications, also used for building modern and dynamic web applications. It is developed to run on multiple environments like Windows, Linux, and macOS. These operating systems provide a rich set of features that make it easy to build and deploy web applications. Some of the key features of ASP.NET Core MVC include dependency injection, routing, model binding, validation, and Razor views for building UI. It also provides support for building RESTful APIs, where developers can create scalable and flexible web applications.

The main problem arises when we want to redirect to the page which we want to occur when we perform any specific event or action like submitting the form or login into the application but by default, it reloads and shows the same page again, and if we want to redirect into the desired page where it is showing the actual updated record, then we can use redirectToAction("page name")method.

How to use the redirectToAction() method?
The redirectToAction() method is used in frameworks like ASP.NET and ASP.NET Core. This method is used to redirect from one web page to the desired page. The RedirectToAction() method is part of the Controller class, which is used to handle incoming HTTP requests. The method takes one or more parameters to specify the action and controller to redirect to.

Here's an example to demonstrate the usage of the RedirectToAction() method in ASP.NET MVC.

Let's say you have a controller named HomeController with two action methods: Index() and About(). The Index() action method displays the home page, and the About() action method displays information about the website.
using System.Web.Mvc;

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult About()
    {
        return View();
    }
}


Let's assume that you want to redirect the user from the Index() action method to the About() action method when a certain condition is met. You can achieve this using the RedirectToAction() method.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        if (/* check condition */) // Replace this with your condition
        {
            return RedirectToAction("About");
        }
        return View();
    }
    public ActionResult About()
    {
        return View();
    }
}

In the example above, if the condition inside the Index() action method evaluates to true, the RedirectToAction() method is called with the parameter "About". This redirects the user to the About() action method, and the associated view is rendered.

The RedirectToAction()  method can also accept additional parameters to pass data between actions. For example

return RedirectToAction("About", new { id = 123 });

In this case, the About() action method can receive the id parameter to perform further processing.

The RedirectToAction() method in ASP.NET is used to redirect users from one action method to another within the same or different controller. It is commonly used in MVC applications for navigation and routing purposes. Using this method, you can control the flow of your application and redirect users based on specific conditions or events.
FAQ'S

Q1. What's the difference between RedirectToAction() and Redirect() methods?
A. The RedirectToAction() method is used to redirect users to another action method within the application, while the Redirect() method is used to redirect users to a different URL or external website.

Q2. Can I redirect to an action method in a different controller?
A. Yes, you can use the RedirectToAction() method to redirect to an action method in a different controller by specifying the controller name as a parameter.

Q3. Is it possible to redirect to an external URL using RedirectToAction()
A. No, the RedirectToAction() method is specifically designed for redirecting within the application. If you need to redirect to an external URL, you should use the Redirect() method and provide the URL as a parameter.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Consuming Services in ASP.NET Core MVC Controller

clock June 23, 2023 12:21 by author Peter

Another interesting feature of ASP.NET Core is service consumption using Dependency Injection. I already provided the overview of Dependency Injection in my earlier articles. Moving further, in this article we will see how one can inject and consume services to controller using dependency injection.

In ASP.NET, you can access services at any stage of your HTTP pipeline through dependency injection. By default, it provides Constructor injection, but it can easily be replaced by any other container of your choice. Before moving ahead, one point is very important to understand and that is lifetime of services.
ASP.NET  Core allows you to configure four different lifetimes for your services.

  • Transient - Created on every request.
  • Scoped - Created once per request.
  • Singleton - Created first time when they are requested.
  • Instance - Created in ConfigureServices method and behaves like a Singleton.

To understand the service consumption inan easier way, we will create a sample application going step-by-step. My example service will provide GUID to the respective controller. So, let's start quickly.

Create a new project - Create a new project using ASP.NET Web Application template as shown below:



Add Service Interface - Create an interface named IGUIDService under Services folder as shown below:
public interface IGUIDService
{
    string GenerateGUID();
}

Add Service Implementation - Create a class named GUIDServiceunder Services folder and provide the implementation of IGUIDService interface as shown below:
public class GUIDService : IGUIDService
{
    public string GenerateGUID()
    {
        return ("Generated GUID is: " + Guid.NewGuid()).ToString();
    }
}

Add a Controller - Next task is to add a Controller namedGUIDController by right clicking on Controllers folder as shown below:

Add a View - Before adding a View, create a folder named under Views folder. Now add a View by right clicking on GUID folder as shown:

Update the code inside View as shown below:

Use Service in Controller - Now instantiate the service and set the data for View as shown below:
public class GUIDController : Controller
{
    private IGUIDService _guidService;

    public GUIDController(IGUIDService guidService)
    {
        _guidService = guidService;
    }
    public IActionResult Index()
    {
        ViewData["GeneratedGUID"] = _guidService.GenerateGUID();
        return View();
    }
}


Register Service - Last step is to register the service in the ConfigureServices method of Startup class as shown below:
public void ConfigureServices(IServiceCollection services)
{
    ...
    ...
    services.AddMvc();
    services.AddInstance<IGUIDService>(new GUIDService());
}

Everything is set. Now run your application and you would be able to see GUID on browser as:

Hope you got an idea on how to inject services in ASP.NET Core 1.0.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Process Filter In MVC

clock May 31, 2023 10:10 by author Peter

Action filter in MVC allows us to manage situations in which we wish to perform an operation prior to and following the execution of a controller action. We create a custom class that inherits the FilterAttribute class and implements the IActionFilter interface for this purpose. After creating the filter, we merely assign the class name to the controller as an attribute.

In this case, the FilterAttribute class allows the class to be used as an attribute, and the IActionFilter interface contains two methods titled OnActionExecuting and OnActionExecuted. OnActionExecuting is executed before the controller method, while OnActionExecuted is summoned after the controller method has been executed. This technique is extremely useful for archiving purposes. So let's examine how we can utilize this filter.
 
Let's begin by adding the MyActionFilter.cs class. Derive this class now from the FilterAttribute and the IActionFilter interfaces. Incorporate your custom logic within the OnActionExecuting and OnActionExecuted methods.Consequently, the code will appear as shown below.  

    public class MyActionFilter : FilterAttribute, IActionFilter  
    {  
        public void OnActionExecuted(ActionExecutedContext filterContext)  
        {  
            //Fires after the method is executed  
        }  
      
        public void OnActionExecuting(ActionExecutingContext filterContext)  
        {  
            //Fires before the action is executed  
        }  
    }  


Simply, apply the class as an attribute on the controller. Add debuggers on both the methods as well as the controller method.

    public class HomeController : Controller  
    {  
        [MyActionFilter]  
        public ActionResult Index()  
        {  
            return View();  
        }  
      
        public ActionResult About()  
        {  
            ViewBag.Message = "Your application description page.";  
            return View();  
        }  
      
        public ActionResult Contact()  
        {  
            ViewBag.Message = "Your contact page.";  
            return View();  
        }  
    }  

Run the Application and debug step by step to see the order of execution of the methods. First, the OnActionExecuting will be executed, then the controller method and finally the OnActionExecuted method.

I hope you enjoyed reading it. Happy coding.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET Core MVC Request Life Cycle

clock May 25, 2023 12:11 by author Peter

The ASP.NET Core MVC Request Life Cycle is a sequence of events, stages or components that interact with each other to process an HTTP request and generate a response that goes back to the client. In this article, we will discuss each and every stage of ASP.NET Core MVC Request Life Cycle in detail.


Middleware
Middleware component is the fundamental building element of the HTTP pipeline of an application. This is a collection of components that are combined to form a request pipeline that can process any incoming request.

Routing

Routing is a component of middleware that implements the MVC framework. With the aid of convention routes and attribute routes, the routing Middleware component determines how incoming requests are mapped to Controllers and action methods.


Controller Initialization

During this phase of the ASP.NET MVC Core Request Life Cycle, controller initialization and execution occur. Controllers are in charge of processing inbound requests. The controller chooses the appropriate action methods based on the supplied route templates.

Method call implementation

After the controllers have been initialized, the action methods are executed and a view containing an HTML document that will be returned to the browser is returned.

Result Execution

During this phase of the ASP.NET MVC Core Request Life Cycle, the response to the initial HTTP request is executed. The MVC view engine renders a view and returns the HTML response if an action method returns a view result. If the result is not of type view, the action method will generate its own response.

Now, we will briefly discuss each phase of Middleware

Middleware component is the fundamental building element of the HTTP pipeline of an application. These are a series of components that comprise a request pipeline to handle any incoming request. Each new request is forwarded to the initial middleware component. After processing an incoming request, the component determines whether to generate a response or pass it on to the next component. Once the request has been processed, the response is sent back via these components.

The majority of middleware components are implemented as isolated classes that generate content. Adding the ContentComponent.cs class will allow us to create a content-generating middleware component.

using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace WebApplication
{
  public class ContentComponent
   {
     private RequestDelegate nextComponent;
     public ContentComponent(RequestDelegate nextMiddleware) => nextComponent = nextMiddleware;
     public async Task Invoke(HttpContext httpContext)
      {
        if (httpContext.Request.Path.ToString().ToLower() == "/edit")
         {
           await httpContext.Response.WriteAsync("This is edit URL component", Encoding.UTF8);
         }
        else
         {
           await nextComponent.Invoke(httpContext);
         }
      }
   }
}

This ContentComponent middleware component is defining a constructor, and inside constructor its taking RequestDelegate object. This RequestDelegate object represents the next middleware component. ContentComponent component also defines an Invoke method. When ASP.NET Core application receives an incoming request, the Invoke method is called.

The HttpContext argument of the Invoke method provides information about the incoming HTTP request and the generated response that will be sent back to the client. The invoke method of  ContentComponent class checks whether incoming request is sent to /edit URL or not. If the request has been sent to /edit url then, in response a text message is sent.

Routing
Routing is a middleware component that implements MVC framework. In ASP.NET Core, the routing system is used to handle MVC URLs. The routing Middleware component decides how an incoming request can be mapped to Controllers and actions methods, with the help of convention routes and attribute routes. Routing bridges middleware and MVC framework by mapping incoming request to controller action methods.

In a particular application, MVC registers one or more routes using MapRoute method. MVC provides default routes that are given a name and a template to match incoming request URLs. The Controllers and action variables are placeholders that are replaced by matching segments of the URL.

These routes are passed into and consumed by routing middleware.

The MVC routing pipeline


In ASP.NET Core, routing maps an incoming request to RouteHandler class, which is then passes as the collection of routes to the routing middleware. The routing middleware executes MVC RouteHandler for each route. If a matching controller and action method is found on a particular route, then the requested data is forwarded to the rest of the MVC framework which will generate a response.

There are two types of routing available in MVC which are:

Convention routing

This routing type uses application wide patterns to match a different URL to various controller action methods. Convention routes represent default possible routes that can be defined with the help of controller and action methods.

Attribute routing
This type of routing is implemented through attributes and applied directly to a specific controller or action method.

The convention routing methodology is implemented inside startup.cs file. In startup.cs, the UseMvc() method registers the routes, that are being supplied to it as a parameter inside MapRoute method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
 app.UseMvc(routes => {
    routes.MapRoute(
   name: "default",
   template: "{controller=Home}/{action=Index}/{id?}");
 });
}


A route attribute is defined on top of an action method inside controller class.
public class MoviesController: Controller {
  [Route(“movies / released / {year}/{month:regex(\\d{4})}”)]
    public ActionResult ByReleaseYear(int year, int month) {
     return Content(year + ”/”+month);
    }
}


Controller Initialization
At this stage, the process of initialization and execution of controllers takes place. Controllers are responsible for handling incoming requests which is done by mapping request to appropriate action method. The controller selects the appropriate action methods (to generate response) on the basis of route templates provided. A controller class inherits from controller base class. A controller class suffix class name with the Controller keyword.


The MVC RouteHandler is responsible for selecting an action method candidate in the form of action descriptor. The RouteHandler then passes the action descriptor into a class called Controller action invoker. The class called Controller factory creates instance of a controller to be used by controller action method. The controller factory class depends on controller activator for controller instantiation.

After action method is selected, instance of controller is created to handle request. Controller instance provides several features such as action methods, action filters and action result. The activator uses the controller type info property on action descriptor to instantiate the controller by name. once the controller is created, the rest of the action method execution pipeline can run.

The controller factory is the component that is responsible for creating controller instance. The controller factory implements an interface called IControllerFactory. This interface contains two methods which are called CreateController and ReleaseController.

Action Method Execution Process

Authorization Filters
Authorization filters authorize or deny any incoming request.

Controller Creation
Instantiate Controller object.

Model Binding
Model Binding bind incoming request to Action method parameters.

Action Filters
OnActionExecuting method is always called before the action method is invoked.

Action Method Execution
Action method inside controller classes executes logic to create Action Result. Action method returns action results to generate response.

Action Filters
OnActionExecuted method called is always called after the action method has been invoked.

Authorization Filters

In ASP.NET Core MVC, there is an attribute called Authorize. Authorize is a filter, which can be applied to an action and it will be called by a MVC Core framework before and after that action or its result are executed.

These filters are used to provide security to application, including user authorization. If authorize attribute is applied to an action method, before the action is executed, the attribute will check if the current user is logged in or not. If not it will redirect the user to the login page. Authorization filters authorize or deny any incoming request.

In the below code example, Authorize Authorization filter(predefined filter) has been used over Index action method.
[Authorize]
public ViewResult Index() {
 return View();
}


The OnAuthorization method authorizes an HTTP request.
namespace WebApplication {
  public interface IAuthorizationFilter: IFilterMetadata {
   void OnAuthorization(AuthorizationFilterContext content);
}

Now I have demonstrated, how to create a custom Authorization filter. A class file called OnlyHttpsAttribute.cs has been created which defines the action filter.
using System;
  using Microsoft.AspNetCore.Http;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.AspNetCore.Mvc.Filters;
  namespace WebApplication {
   public class OnlyHttpsAttribute: IAuthorizationFilter {
    public void OnAuthorization(AuthorizationFilterContext approve) {
     if (!approve.HttpContext.Request.IsHttps) {
      approve.Result =
       new StatusCodeResult(StatusCodes.Status403Forbidden);
     }
    }
   }
}


In the below example, OnlyHttps attribute has been applied to the Home controller
using Microsoft.AspNetCore.Mvc;
using WebApplication;
namespace Controllers {
 [OnlyHttps]
 public class HomeController: Controller {
  public ViewResult Index() => View("Message",
   "this URL is working fine");
   }
}

Model Binding
Model binding maps incoming request to action method parameters. Action method parameters are inputs for an action method. Using data values acquired from HTTP request, model binding creates objects that an action method takes as an argument.

The model binders are the components which provide data values from incoming request to invoke action methods. The model binders search for these data values under three scenarios which are
    Form data values
    Routing variables
    Query strings

Each of these sources are examined in sequence until and unless an argument value is found.

Let’s consider a controller class as follows
using System.Linq;
using System.Web.Mvc;
namespace project.Controllers {
 public class CustomerController: Controller {
  public ActionResult Edit(int id) {
   return Content("id=", +id);
  }
 }
}


Now, suppose i requested an URL as /Customer/Edit/1

Here 1 is the value of id property. MVC translated that part of the URL and used it as the argument when it called the Edit method in the Customer controller class to service the request.To invoke the Edit method, MVC requires a certain type of value for the argument id, therefore model binding provide data values to invoke action methods.

Action Filters
Action filters are used to execute tasks instantly before and after action method execution is performed. In order to apply some logic to action methods, without having to add extra code to the controller class, action filters can be used either above the action method itself or above the Controller class.

Action filter implements two types of interfaces which are IActionFilter and IAsyncActionFilter.

The IActionFilter interface which defines action filter is as follows
public interface IActionFilter: IFilterMetadata {
 void OnActionExecuting(ActionExecutingContext content);
 void OnActionExecuted(ActionExecutedContext content);
}

The method OnActionExecuting is always called before the action method is invoked, and the method OnActionExecuted is always called after the action method has been invoked, whenever an action filter is applied to an action method.

Whenever an action filter is created, the data is provided using two different context classes, ActionExecutingContext and ActionExecutedContext.

Now I will demonstrate, how to create a custom action filter by deriving a class from the ActionFilterAttribute class. A class file called ActionAttribute.cs has been created which defines the action filter.
using Microsoft.AspNetCore.Mvc.Filters;
namespace WebApplication {
 public class ActionAttribute: ActionFilterAttribute {
  private Stopwatch a;
  public override void OnActionExecuting(ActionExecutingContext content) {
   a = Stopwatch.StartNew();
  }
  public override void OnActionExecuted(ActionExecutedContext content) {
   a.Stop();
   string output = "<div> calculated time is: " + $" {a.Elapsed.TotalMilliseconds} ms </div>";
   byte[] bytes = Encoding.ASCII.GetBytes(output);
   content.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
  }
 }
}

In the below example, Action attribute has been applied to the Home controller
using Microsoft.AspNetCore.Mvc;
using WebApplication;
namespace Controllers {
 [Action]
 public class HomeController: Controller {
  public ViewResult Index() => View("Message",
   "This index action is executed between action attribute");

 }
}

Action Method Execution
Action methods return objects that implements the IActionResult interface from the Microsoft.AspNetCore.Mvc namespace. The various types of response from the controller such as rendering a view or redirecting the client to another URL, all these responses are handled by IActionResult object, commonly known as action result.

When an an action result is returned by a specific action method, MVC calls its ExecuteResultAsync method, which generates response on behalf of the action method. The ActionContext argument provides context data for generating the response, including the HttpResponse object.

Controllers contain Action methods whose responsibility is to generate a response to an incoming request. An action method is any public method inside a controller that responds to incoming requests.
Public class HomeController: Controller {
 Public IActionResult Edit() {
  Return View();
 }
}


Here, Edit action method is defined inside Home controller.
using Microsoft.AspNetCore.Mvc;
using WebApplication23;
namespace WebApplication23.Controllers {
 public class HomeController: Controller {
  public ViewResult Index() => View("Form");
  };
 }
}


Here, Index method is defined inside Home controller, which is returning a view.

Result Execution

The action method returns action result. This action result is the base class for all action results in asp.net mvc. Depending on the result of an action method, it will return an instance of one of the classes that derive from action result.

Different types of action result are

TYPES HELPER METHOD DESCRIPTION
ViewResult View() Renders a view and retun HTML content
PartialViewResult PartialView() Returns partial view
ContentResult Content() Returns simple text
RedirectResult Rediect() Redirect result to URL
RedirectToRouteResult RedirectToAction() Redirect to an action method
JsonResult Json() Returns serialized json object
FileResult File() Returs a file
HttpNotFoundResult HttpNotFound() Returns not found or 404 error
EmptyResult   When action does not return values

During this stage of ASP.NET MVC Core Request Life Cycle, result i.e. the response generated to the original HTTP request, is executed. If an action method returns a view result, the MVC view engine renders a view and returns the HTML response. If result is not of view type, then action method will generate its own response.

using Microsoft.AspNetCore.Mvc;
using WebApplication23.example;
namespace WebApplication23.Controllers {
  public class HomeController: Controller {
   public ViewResult Index() => View("Form");
   public ViewResult ReceiveForm(string name, string state) => View("Details",$ "{name} lives in {state}");
}

In the above example Index action method is returning a view result, therefore the MVC view engine renders a view and returns the HTML response, which is a simple form.

In this article, we have discussed each and every stage of ASP.NET Core MVC Request Life Cycle in detail. All of the stages have been described with proper coding examples and life cycle diagrams.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Learn About Filters In ASP.NET MVC

clock December 30, 2020 12:17 by author Peter

As part of this article, we will learn about ASP.Net MVC filters, their different types and we will create a custom log Action Filter using Visual Studio. So without wasting any time let's start.

What are ASP.Net MVC filters
In an ASP.Net MVC Web application, we have action methods defined in controllers that call from different views. For example, when the user clicks on some button on the view, a request goes to the designated controller and then the corresponding action method. Within this flow, sometimes we want to perform logic either before an action method is called or after an action method runs.
 
To fulfill the above condition ASP.Net MVC provides us filters. Filters are the custom classes that provide us with an option to add pre-action and post-action behavior to controller action methods.
 
ASP.NET MVC framework supports four different types of filters:

  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters

Note
They are executed in the order listed above.
 
Authorization filters
In ASP.NET MVC web application by default, all the action methods of all the controllers can be accessible for all the users (for both authenticated and anonymous users both). For this, if we want to restrict some action methods from anonymous users or we want to allow the action methods only to an authenticated user, then you need to use the Authorization Filter in MVC.
 
The Authorization Filter provides two built-in attributes such as Authorize and AllowAnonymous. We can decorate our action methods with the Authorize attribute which allows access to the only authenticated user and we can use AllowAnonymous attribute to allow some action method to all users.
 
We can also create custom Authorization filters for this we have to implement IAuthenticationFilter interface and have overrides its OnAuthentication() and OnAuthenticationChallenge(). We are going deep into it.
 
Action filters
In the ASP.NET MVC web application, action filters are used to perform some logic before and after action methods. The output cache is one of the built-in action filters which we can use in our action methods.
    [OutputCache(Duration=100)]
    public ActionResult Index()
    {
       return View();
    }

We can also create a custom action filter either by implementing IActionFilter interface and FilterAttribute class or by deriving the ActionFilterAttribute abstract class. As part of this article, I am covering creating a custom action filter using the ActionFilterAttribute abstract class.
 
ActionFilterAttribute includes the following method to override it:
    void OnActionExecuted(ActionExecutedContext filterContext)
    void OnActionExecuting(ActionExecutingContext filterContext)
    void OnResultExecuted(ResultExecutedContext filterContext)
    void OnResultExecuting(ResultExecutingContext filterContext)

We will see this in detail below.
 
Result filters
 
In an ASP.NET MVC web application, result filters are used to perform some logic before and after a view result is executed. For example, we might want to modify a view result right before the view is rendered.
 
Exception filters
 
In the ASP.NET MVC web application, we can use an exception filter to handle errors raised by either our controller actions or controller action results. We also can use exception filters to log errors.
 
Creating a Log Action Filter
Open Visual Studio and create a new ASP.NET Web Application

Choose Empty, select “MVC” and then click the OK button.

Add a ‘Filters’ folder and create a new class LogActionFilter.cs under it:
    using System.Diagnostics;  
    using System.Web.Mvc;  
    using System.Web.Routing;  
      
    namespace FiltersMVC.Filters  
    {  
        public class LogActionFilter : ActionFilterAttribute  
      
        {  
            public override void OnActionExecuting(ActionExecutingContext filterContext)  
            {  
                Log("OnActionExecuting", filterContext.RouteData);  
            }  
      
            public override void OnActionExecuted(ActionExecutedContext filterContext)  
            {  
                Log("OnActionExecuted", filterContext.RouteData);  
            }  
      
            public override void OnResultExecuting(ResultExecutingContext filterContext)  
            {  
                Log("OnResultExecuting", filterContext.RouteData);  
            }  
      
            public override void OnResultExecuted(ResultExecutedContext filterContext)  
            {  
                Log("OnResultExecuted", filterContext.RouteData);  
            }  
      
      
            private void Log(string methodName, RouteData routeData)  
            {  
                var controllerName = routeData.Values["controller"];  
                var actionName = routeData.Values["action"];  
                var message = $"{methodName} controller:{controllerName} action:{actionName}";  
                Debug.WriteLine(message, "Action Filter Log");  
            }  
        }  
    }  


We overrides OnActionExecuting(), OnActionExecuted(), OnResultExecuting(), and OnResultExecuted() methods all are calling the Log() method. The name of the method and the current route data is passed to the Log() method. The Log() method writes a message to the Visual Studio Output window.
 
Now, add HomeController.cs under the Controllers folder.
    using FiltersMVC.Filters;  
    using System.Web.Mvc;  
      
    namespace FiltersMVC.Controllers  
    {  
        [LogActionFilter]  
        public class HomeController : Controller  
        {  
            // GET: Home  
            public ActionResult Index()  
            {  
                return View();  
            }  
        }  
    }  

After adding the above files our folder structure will look like this:


Now run the application, we can see the results in the “Output” window.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Ajax.ActionLink and Html.ActionLink in MVC

clock December 16, 2020 08:26 by author Peter

In this article, you will learn the use of the Ajax.ActionLink helper and Html.ActionLink. I will compare both to show you how they differ. Okay, let's begin with Html.ActionLink.

Html.ActionLink
Html.ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action. Here are some samples of Html.ActionLink.
 
If you want to navigate to the same controller's action method, use the one given below. Razor is smart enough to assume the first param is link text and the second param is the action method name, if it finds only two parameters.
    @Html.ActionLink("Click here", // <-- Link text  
                     "Index" // <-- Action Method Name  
                     )  

It's rendered HTML: <a href="/">Click here</a>
 
If you want to navigate to a different controller's action method, use the one given below. You can even avoid typing "null" for the route value and htmlArguments. Here also, razor will assume the first param as link text, the second param as the action method name and the third param as the controller name, if it finds three parameters.
    @Html.ActionLink("Click here", // <-- Link text  
                     "About", // <-- Action Method Name  
                     "Home", // <-- Controller Name  
                     null, // <-- Route value  
                     null // <-- htmlArguments  
                     )  


It's rendered HTML: <a href="/Home/About">Click here</a>
 
If you want to navigate to the same controller's action method then use the one given below. Here razor will assume the first param is link text, second param is an action method and the third param is the route value. We can avoid typing "null" for the htmlArgument; that works fine.
    @Html.ActionLink("Edit", // <-- Link text  
                     "Edit", // <-- Action Method Name  
                     new { id=item.CustomerID }, // <-- Route value  
                     null // <-- htmlArguments  
                    )  


It's rendered HTML: <a href="/Home/Edit/187">Edit</a>
 
If you want to navigate to the same controller's action method then use the one given below. Here razor will assume the first param is link text, second param is the action method and the third param is the route value. Instead of typing "null" or avoiding the htmlAttribute, I am using the "class" attribute with "ui-btn" as the name.
    @Html.ActionLink("Edit", // <-- Link text  
                     "Edit", // <-- Action Method Name  
                     new { id=item.CustomerID }, // <-- Route value  
                     new {@class="ui-btn"} // <-- htmlArguments  
                    )  

It's rendered HTML: <a class="ui-btn" href="/Home/Edit/187">Edit</a>
 
What if one wants rendered HTML to be as given below that is an application-specific anonymous attribute:
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>
 
If you try to do it as given below, you will get the error:

The reason is that we can't use an anonymous property/attribute having a dash in the name. Use an underscore instead of a dash and MVC will automatically replace the underscore with a dash in the rendered HTML, here it is:
    @Html.ActionLink("Edit", // <-- Link text  
                     "Edit", // <-- Action Method Name  
                     new { id=item.CustomerID }, // <-- Route arguments  
                     new {@class="ui-btn", data_val="abc"} // <-- htmlArguments  
                    )  

That's how we work around in MVC for any anonymous property.
 
Note: You can notice that Html.ActionLink takes at least two parameters as Html.ActionLink(LinkText, ActionMethod).
 
Ajax.ActionLink

Ajax.ActionLink is much like the Html.ActionLink counterpart, it also creates the hyperlink <a href="">Click here</a> but when the user clicks it and has a JavaScript enabled browser, Ajax.ActionLink sends the asynchronous request instead of navigating to the new URL. With the Ajax.ActionLink we specify what controller's action method is to be invoked and also specify what to do with the response coming back from the action method.
 
Let's create an Ajax.ActionLink helper that will send an asynchronous request to the action method and will update the DOM with the result.
 
Step 1
At first we need an Ajax.ActionLink that will send the async request, so here we go:
    <h2>Customers</h2>  
    @Ajax.ActionLink("Customer from Germany", // <-- Text to display  
                     "Germany", // <-- Action Method Name  
                     new AjaxOptions  
                     {  
                         UpdateTargetId="CustomerList", // <-- DOM element ID to update  
                         InsertionMode = InsertionMode.Replace, // <-- Replace the content of DOM element  
                         HttpMethod = "GET" // <-- HTTP method  
                     })  
    @Ajax.ActionLink("Customer from Mexico", // <-- Text to display  
                     "Mexico", // <-- Action Method Name  
                     new AjaxOptions  
                     {  
                         UpdateTargetId="CustomerList", // <-- DOM element ID to update  
                         InsertionMode = InsertionMode.Replace, // <-- Replace the content of DOM element  
                         HttpMethod = "GET" // <-- HTTP method  
                     })  
    <div id="CustomerList"></div>  
    @section scripts{  
        @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js")  
    }  


In the code above, you can see that I have created two Ajax.ActionLinks, one to display the list of customers from Germany and another to display the list of customers from Mexico, all will be called asynchronously. We have not specified which controller to access, so by default it will look in the same controller. Here is the generated HTML by both Ajax.ActionLink.
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>
 
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a>
 

The unobtrusive jQuery uses the data-ajax prefix for JavaScript to invoke action methods on the server rather than intrusively emitting inline client scripts.
 
When we will click the link it will make a GET HTTP method call and the returned result will be updated to a DOM element by Id "CustomerList".
 
Always remember to place a reference of the jquery.unobtrusive-ajax.js library file after jquery-{version}.js file references, we can use bundling also. If you don't include the jquery.unobtrusive-ajax.js or do it incorrectly, then when you click the link to the view list of countries, an async result will be opened on the new browser tab.
 
Also, ensure that the unobtrusive JavaScript is enabled in your web.config (it should be by default).
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />  

Step 2
Now, let's go ahead and implement the "Germany" and "Mexico" action methods that will return a PartialView.
    NorthwindEntities db = new NorthwindEntities();  
    public PartialViewResult Germany()  
    {  
        var result = from r in db.Customers  
                        where r.Country == "Germany"  
                        select r;  
        return PartialView("_Country", result);  
    }  
    public PartialViewResult Mexico()  
    {  
        var result = from r in db.Customers  
                        where r.Country == "Mexico"  
                        select r;  
        return PartialView("_Country", result);  
    }  


So, in both of the PartialViewResult methods I have used a LINQ query that will filter records on country and then pass the results to a partial view page "_Country.cshtml". I have placed this file in the "Shared" folder so that any view can access it. Let's move on to see the partial view page "_Country.cshtml".
 
Step 3
I made this view page strongly typed by using @model and then iterated through the model data to create a nice tabular format.
    @model IEnumerable<MvcActionLink.Models.Customer>  
    <table>  
        <tr>  
            <th>  
                @Html.DisplayNameFor(model => model.ContactName)  
            </th>  
            <th>  
                @Html.DisplayNameFor(model => model.Address)  
            </th>  
        </tr>  
    @foreach (var item in Model) {  
        <tr>  
            <td>  
                @Html.DisplayFor(modelItem => item.ContactName)  
            </td>  
            <td>  
                @Html.DisplayFor(modelItem => item.Address)  
            </td>  
        </tr>  
    }  
    </table>  


Now, you all set to run the application.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Display A Document From SQL Server To A Web Page In ASP.NET MVC

clock October 27, 2020 10:19 by author Peter

In this blog post, I'll discuss a useful yet easy to implement document viewer API. Using that you can display a source file (e.g. Word, Presentation, Diagram, PSD) from your server to your browser without downloading it.
 

Some Use-Cases
    Display a Word resume to a user in a web browser
    Render a Visio Diagram on the web page
    View a Presentation or a Slide online without downloading it

Implementation
 
Now as the use-cases are clear, we will dive into the API implementation. It'll be an ASP.NET MVC application. We'll pull data/documents from the database and save it to a stream. You have to specify the file format in order to render it correctly. The source document will be then rendered to HTML. Eventually, our controller will return this stream to the View/browser.  
    public ActionResult Index()  
    {  
         License lic = new License();  
         lic.SetLicense(@"D:/GD Licenses/Conholdate.Total.NET.lic");  
         MemoryStream outputStream = new MemoryStream();  
         //specify just the file name if you are pulling the data from database   
         string fileName = "sample.pdf";  
      
         FileType fileType = FileType.FromExtension(Path.GetExtension(fileName));  
      
         using (Viewer viewer = new Viewer(() => GetSourceFileStream(fileName), () => new LoadOptions(fileType)))  
         {  
               HtmlViewOptions Options = HtmlViewOptions.ForEmbeddedResources(  
                    (pageNumber) => outputStream,  
                    (pageNumber, pageStream) => { });  
               viewer.View(Options);  
         }
         outputStream.Position = 0;  
         return File(outputStream, "text/html");  
                   
    }  
    private Stream GetSourceFileStream(string fileName) =>  
                new MemoryStream(GetSourceFileBytesFromDb(fileName));  
      
    //TODO: If you want to pull the data from the DB  
    private byte[] GetSourceFileBytesFromDb(string fileName) =>  
                System.IO.File.ReadAllBytes(fileName);  


Have a look at this image/screenshot. We displayed a PDF from Server to Browser.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ViewBag, ViewData And TempData In MVC

clock October 23, 2020 09:44 by author Peter

ViewBag, ViewData, and TempData all are objects in ASP.NET MVC and these are used to pass the data in various scenarios.

The following are the scenarios where we can use these objects.
    Pass the data from Controller to View.
    Pass the data from one action to another action in the same Controller.
    Pass the data in between Controllers.
    Pass the data between consecutive requests.

ViewBag
ViewBag is a dynamic object to pass the data from Controller to View. And, this will pass the data as a property of object ViewBag. And we have no need to typecast to read the data or for null checking. The scope of ViewBag is permitted to the current request and the value of ViewBag will become null while redirecting.
 
Ex Controller
    Public ActionResult Index()  
    {  
        ViewBag.Title = “Welcome”;  
        return View();  
    }  

View
    <h2>@ViewBag.Title</h2>  

ViewData
ViewData is a dictionary object to pass the data from Controller to View where data is passed in the form of key-value pair. And typecasting is required to read the data in View if the data is complex and we need to ensure null check to avoid null exceptions. The scope of ViewData is similar to ViewBag and it is restricted to the current request and the value of ViewData will become null while redirecting.
 
Ex
Controller:

    Public ActionResult Index()  
    {  
        ViewData[”Title”] = “Welcome”;  
        return View();  
    }  


View
    <h2>@ViewData[“Title”]</h2>  

TempData
TempData is a dictionary object to pass the data from one action to other action in the same Controller or different Controllers. Usually, TempData object will be stored in a session object. Tempdata is also required to typecast and for null checking before reading data from it. TempData scope is limited to the next request and if we want Tempdata to be available even further, we should use Keep and peek.
 
Ex - Controller
    Public ActionResult Index()  
    {  
        TempData[”Data”] = “I am from Index action”;  
        return View();  
    }  

    Public string Get()  
    {  
        return TempData[”Data”] ;  
    }  

To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.
 
Hope you have understood the concept of ViewBag, ViewData, and TempData.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in