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 :: Various Return Types From MVC Controller

clock February 23, 2024 07:11 by author Peter

This is a popular question in.NET job interviews, as I've heard from several acquaintances. Developers with limited hands-on expertise with MVC should be able to respond to the question because the scenario is typical and requires returning anything from the controller to the presentation environment on a regular basis. We are extremely familiar with the "ActionResult" class, which is the base class for many classes and can return an object from those classes. The class structure is as follows:

System.Object
System.Web.Mvc.ActionResult

    System.Web.Mvc.ContentResult
    System.Web.Mvc.EmptyResult
    System.Web.Mvc.FileResult
    System.Web.Mvc.HttpStatusCodeResult
    System.Web.Mvc.JavaScriptResult
    System.Web.Mvc.JsonResult
    System.Web.Mvc.RedirectResult
    System.Web.Mvc.RedirectToRouteResult
    System.Web.Mvc.ViewResultBase


In this example, we will see all of the derived classes that is inherited from the “ActionResult” base class. So, let's start one by one.
 
Return View
This is a most common and very frequently used type. We see that we can pass eight parameters when we return the view. We can specify the view name explicitly or may not.

Return partial View

The concept of a partial view is quite similar to the master page concept used in Web Form applications. The partial view is simply a pagelet that may be returned from the controller and combines with the main view to create a single tangible HTML page.

It may require four parameters to render in the partial view.
 
Redirect
This is comparable to the Response.redirect() and Server.Transfer() routines. It uses the URL path to redirect, however with MVC, we can instead use Response.Redirect() or Server.Transfer() instead.

Redirect To Action
Sometimes it is necessary to call another action after completion of one action, this is very similar to a function call in traditional function oriented programming or Object Oriented Programming. It may take 6 parameters. The first parameter is very simple, only action name.

Return content
This is useful when we want to return a small amount of strings from a controller/action. It takes three parameters. The first one is a simple string and the remaining two are strings with little information.

Return JavaScript
When we wanted to return a JavaScript string, we may use this function. It takes only one parameter, the string only.

Return File
We are allowed to return a binary file if needed from a controller. It takes 6 parameters maximum.

Conclusion
Those are all of the return types in an action in an MVC controller, but we rarely use them; in my limited experience, users prefer to return View() from the action. What say you? Have fun learning.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Result vs. ActionResult in ASP.NET MVC

clock February 7, 2024 08:54 by author Peter

ViewResult and ActionResult are two classes in ASP.NET MVC that are used to display the output of an action function.

1. Action-Result
For all action result kinds in ASP.NET MVC, ActionResult is the abstract base class. It serves as the foundation class for many result kinds, including JsonResult, ViewResult, and RedirectResult. Usually, you specify ActionResult as the return type when you define an action method in a controller.

As an illustration

public ActionResult MyAction()
{
    // Action logic here
    return View(); // Returns a ViewResult
}

2. ViewResult
ViewResult is a specific type of ActionResult that represents a result that renders a view. When you return a ViewResult from an action method, it means that the framework should render a view associated with the action.

For example

public ViewResult MyAction()
{
    // Action logic here
    return View(); // Returns a ViewResult
}

Key differences in nutshell

The following are the key differences in nutshell.

  • ActionResult is more general: ActionResult is a more general type, and it can represent different types of results, not just views. It allows for flexibility in returning various result types.
  • ViewResult is specific to views: ViewResult is a specific type derived from ActionResult and is used when you specifically want to return a view from an action method.
  • ViewResult simplifies return type: If your action method is intended to return a view, using ViewResult directly can make your code more explicit and easier to understand.
  • ActionResult provides more options: If your action method needs to return different types of results based on certain conditions, using ActionResult allows you to return different types of results (e.g., RedirectResult, JsonResult, etc.) from the same action.

Moreover, in practice, you can often use ViewResult directly when you know your action will always return a view. If you need more flexibility or want to return different types of results, using ActionResult allows for that versatility.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Data Transfer Using TempData in ASP.NET Core MVC Controllers

clock January 30, 2024 06:34 by author Peter

Using TempData, you may transfer temporary data between controllers in ASP.NET Core MVC. A dictionary called TempData can be used to transfer information between controllers both during the current request and the one that comes after. Here's how you can make this happen.

Configure the First Controller's TempData
Assign the data you wish to pass to the TempData in your first controller action.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Student student)
{
    if (ModelState.IsValid)
    {
        _context.Add(student);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }
    // Transfer the Complete Student Object to the Teacher
    TempData["student"] = student;
    return RedirectToAction("Index","Teacher");
}

Complete Student Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DataTransferBetweenControllersinASPNETCoreMVC.DatbaseContext;
using DataTransferBetweenControllersinASPNETCoreMVC.Models;

namespace DataTransferBetweenControllersinASPNETCoreMVC.Controllers
{
    public class StudentsController : Controller
    {
        private readonly AppDbContext _context;

        public StudentsController(AppDbContext context)
        {
            _context = context;
        }

        // GET: Students
        public async Task<IActionResult> Index()
        {
            return View(await _context.Students.ToListAsync());
        }

        // GET: Students/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .FirstOrDefaultAsync(m => m.Id == id);
            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

        // GET: Students/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Students/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Student student)
        {
            if (ModelState.IsValid)
            {
                _context.Add(student);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            // Transfer the Complete Student Object to Teacher
            TempData["student"] = student;
            return RedirectToAction("Index","Teacher");
        }

        // GET: Students/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students.FindAsync(id);
            if (student == null)
            {
                return NotFound();
            }
            return View(student);
        }

        // POST: Students/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,RollNo,Section,Program")] Student student)
        {
            if (id != student.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(student);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!StudentExists(student.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(student);
        }

        // GET: Students/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .FirstOrDefaultAsync(m => m.Id == id);
            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

        // POST: Students/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var student = await _context.Students.FindAsync(id);
            if (student != null)
            {
                _context.Students.Remove(student);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool StudentExists(int id)
        {
            return _context.Students.Any(e => e.Id == id);
        }
    }
}


Retrieve TempData in the Second Controller
In your second controller action, retrieve the TempData.
// GET: Teachers
public async Task<IActionResult> Index()
{
    // Recieve the Student Object data and then keep the data
    // Keep TempData for the next request
    var studentData = TempData["student"];
    TempData.Keep();
    return View(await _context.Teachers.ToListAsync());
}


Complete Teacher Controller Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using DataTransferBetweenControllersinASPNETCoreMVC.DatbaseContext;
using DataTransferBetweenControllersinASPNETCoreMVC.Models;

namespace DataTransferBetweenControllersinASPNETCoreMVC.Controllers
{
    public class TeachersController : Controller
    {
        private readonly AppDbContext _context;

        public TeachersController(AppDbContext context)
        {
            _context = context;
        }

        // GET: Teachers
        public async Task<IActionResult> Index()
        {
            // Recieve the Student Object data and then keep the data
            var studentData = TempData["student"];
            TempData.Keep();
            return View(await _context.Teachers.ToListAsync());
        }

        // GET: Teachers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teachers
                .FirstOrDefaultAsync(m => m.Id == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // GET: Teachers/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Teachers/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,Course,Department")] Teacher teacher)
        {
            if (ModelState.IsValid)
            {
                _context.Add(teacher);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(teacher);
        }

        // GET: Teachers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teachers.FindAsync(id);
            if (teacher == null)
            {
                return NotFound();
            }
            return View(teacher);
        }

        // POST: Teachers/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Course,Department")] Teacher teacher)
        {
            if (id != teacher.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(teacher);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TeacherExists(teacher.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(teacher);
        }

        // GET: Teachers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var teacher = await _context.Teachers
                .FirstOrDefaultAsync(m => m.Id == id);
            if (teacher == null)
            {
                return NotFound();
            }

            return View(teacher);
        }

        // POST: Teachers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var teacher = await _context.Teachers.FindAsync(id);
            if (teacher != null)
            {
                _context.Teachers.Remove(teacher);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool TeacherExists(int id)
        {
            return _context.Teachers.Any(e => e.Id == id);
        }
    }
}


Keeping TempData for Subsequent Requests
By default, TempData is meant for a single subsequent request. If you want to persist TempData for more than one subsequent request, you can use the Keep method.
// GET: Teachers
public async Task<IActionResult> Index()
{
    // Recieve the Student Object data and then keep the data
    var studentData = TempData["student"];
    TempData.Keep();
    return View(await _context.Teachers.ToListAsync());
}

Conclusion

TempData is an efficient way to pass temporary data across controllers in ASP.NET Core MVC. You can save and retrieve information for the current request and the one that follows using TempData. You can enable data sharing between several components of your application by setting TempData in one controller and retrieving it in another.

Keep in mind that TempData is only meant to be read once before being marked for deletion. If you need to store the data for more than one request, use the Keep method.

A handy way to share transient data between controllers when a user interacts with your ASP.NET Core MVC application is via TempData.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Using Postman for ASP.NET MVC 5 API Testing

clock January 11, 2024 06:50 by author Peter

Developers can send calls to an API and receive results using Postman, a popular tool for testing APIs. It offers an easy-to-use interface for creating, testing, and documenting RESTful web services. We will look at using Postman for API testing in an ASP.NET MVC 5 application in this article.

Required conditions
    Postman installed on your computer and an ASP.NET MVC 5 project setup in Visual Studio
    basic familiarity with API development and ASP.NET MVC

Configuring the API
Step 1: Launch Visual Studio, then open the ASP.NET MVC 5 project template.
Step 2: Right-click on the "Controllers" folder and choose "Add" > "Controller" to add a new Controller to the project.

Step 3: Build and launch the program to make sure everything is operating as it should.

Postman is Used for API Testing
Step 1: Launch Postman and click the "New" dropdown menu, then choose "Request" to start a new request.
Step 2: Type your API endpoint's URL into the address bar.
Step 3: From the dropdown menu next to the address bar, choose the HTTP method you wish to use (GET, POST, PUT, DELETE, etc.).

Click on the appropriate tabs to add headers, query parameters, or request body data, if necessary.

Step 4: To send the request and get the answer, click the "Send" button.
The response's headers, content, and status code will all be shown in the lower panel.

Examining Various API Techniques

  • GET Request: Just enter the API URL and choose the GET method to test a GET request. If necessary, you can add query parameters.
  • POST Request: Choose the POST method and input the API URL to test a POST request. Using the "Body" tab, add request body data and select the desired format (x-www-form-urlencoded, form-data, raw, etc.).
  • PUT Request: Choose the PUT method, input the API URL, and supply the request body data in order to test a PUT request.
  • DELETE Request: Choose the DELETE method and input the API URL to test a DELETE request.

Managing the Authentication Process
You can add authentication headers or tokens in Postman if your API requires authentication. Before submitting the request, add the required authentication information in the "Authorization" or "Headers" tab.

Examining the Reaction

Postman presents the body, headers, and response status code in an organized manner. By examining the status code and contrasting it with the anticipated outcome, you may verify the response. You can also use XPath or JSONPath syntax to extract particular data from the response body.

Postman can make API testing more simpler and is a very useful tool for this purpose. In this post, we looked at using Postman to test an ASP.NET MVC 5 application's API. You may easily test various API methods, manage authentication, and examine the answer by following the above-described processes.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How Do You Make An ASP.NET Core MVC Application?

clock November 9, 2023 06:17 by author Peter

We will learn how to develop an ASP.NET Core MVC web application step by step in this tutorial. Web applications built with ASP.NET Core MVC are noted for their adaptability, scalability, and ability to meet a wide range of business requirements. By the end of this tutorial, you will have a firm grasp on the core principles and practical actions required to get started with your own ASP.NET Core MVC project.

What exactly is ASP.NET Core?
Microsoft's ASP.NET Core is an open-source, cross-platform framework for developing modern, cloud-based, and scalable online applications.

What are the benefits of using ASP.NET Core?

  • ASP.NET Core is cross-platform, which means you can write and run applications on Windows, Linux, and macOS. Because of its adaptability, it is suited for a wide range of situations.
  • High Performance: ASP.NET Core is built for speed and scalability. It employs asynchronous programming and supports real-time technologies such as WebSockets and SignalR.
  • Open Source: Because ASP.NET Core is open source, you can view the source code and contribute to the community. It's being developed openly on GitHub, which encourages cooperation and improvement.
  • ASP.NET Core emphasizes current development approaches such as dependency injection, integrated support for popular front-end frameworks such as Angular and React, and built-in support for RESTful APIs.
  • Cross-platform Tools: ASP.NET Core comes with a set of cross-platform tools, including the .NET CLI, which simplifies development, testing, and deployment processes.
  • Support for Microservices: ASP.NET Core is well-suited for microservices architecture, allowing you to build modular, independently deployable services that can scale individually.
  • Integrated Security: ASP.NET Core provides built-in security features, such as identity and authentication, that help developers protect their applications against common threats.
  • Extensible Middleware: Middleware in ASP.NET Core is highly customizable, allowing developers to add or remove components easily to tailor their application's behavior.
  • Docker Support: ASP.NET Core has excellent support for Docker containers, making it straightforward to containerize your applications for easier deployment and scaling.
Let's get started with an ASP.NET Core MVC web application.

Step 1: Launch Visual Studio.

Launch Visual Studio (I'm using 2022).
When Visual Studio opens, in the image below, click on Create a New Project.

Step 2: Select a Project Template
All languages, All platforms, and All project kinds will be displayed. As seen in the figure below, I used the ASP.NET Core Web App (Model-View-Controller) Template.


After selecting a project template, click Next.
Step 3: Establish the Project Name and Location

The following options are available in the project configuration window:,

  • Project Name: You can name your project whatever you want.
  • Location: Select where you want to save the project files on your machine's hard drive. I chose the Project/VS folder on the machine's E drive, which is presumably different on your PC.
  • Solution Name: The solution name is auto-generated based on the project name, but you can alter it to something else.

In addition, there is a checkbox. If you checked it, the solution file (.sln) and project files will be saved in the same directory. Now, select the bare minimum of details for clarity, as illustrated in the image below.

After defining the necessary details, click Next.

Step 4: Select a Target Framework
Choose the target framework.NET 6, which is the most recent, or choose according on your needs. Skip the rest of the details for clarity, as illustrated in the image below.


After providing the required details, click the Create button. It will create the ASP.NET Core MVC web application, as shown in step 5.

Step 5. Understanding ASP.NET Core MVC Folder Structure

The following is the default folder structure of the ASP.NET Core ASP.NET MVC application.


Let's understand the preceding project folder structure in brief.

In ASP.NET Core MVC, the project structure is organized to promote a clean and maintainable architecture. Here's a typical project structure for an ASP.NET Core MVC application.

  • Controllers: This is where you define your controller classes. Controllers handle incoming HTTP requests and contain action methods.
  • Models: In the Models folder, you define your data models. These models represent the structure of your application's data. You might have separate subfolders for different types of models (e.g., ViewModels, DataModels).
  • Views: The Views folder is where you store your view files. These views are responsible for rendering the HTML that's sent to the client. You often have subfolders here corresponding to the controller names, which helps organize the views.
  • wwwroot: This folder contains static files like CSS, JavaScript, and images that are directly accessible to the client.
  • Startup.cs: This file contains the startup configuration for your application, including configuring services and middleware.
  • appsettings.json: This JSON file is used to store configuration settings for your application, such as database connection strings.
  • Program.cs: This is the entry point of your application. It contains the Main method that sets up the web host.
  • wwwroot: This is where you place static files, such as CSS, JavaScript, and images, that are served directly to clients.
  • Areas (optional): If you are using areas in your application to organize controllers and views, you will have a folder for each area.
  • Data (optional): You can have a separate folder for data-related code, such as database context and migrations.
  • Services (optional): You can create a folder for service classes that provide business logic and are used by your controllers.
  • ViewComponents (optional): If you are using view components, you can organize them in this folder.
  • Filters (optional): You may create custom action filters and store them in this folder.
  • Extensions (optional): For extension methods and helper classes that can be reused throughout the application.
  • Resources (optional): For storing localization resources if you are supporting multiple languages.
  • Tests (optional): If you are writing unit tests, you can create a separate folder for your test projects.
  • Properties (auto-generated): This folder may include the AssemblyInfo.cs file and other assembly-related information.

It's important to note that while this is a common structure, it's not set in stone, and you can adapt it to fit the specific requirements of your project. ASP.NET Core is flexible in this regard, allowing you to organize your code as you see fit while following best practices for maintainability and scalability.

Step 6. Run the ASP.NET Core MVC Application

You can run the application with default contents or let open the Index.cshtml file and put some contents there. Now press F5 on the keyboard or use the run option from Visual Studio to run the application in the browser. After running the application, it will show in the browser, as shown in the following image.

I hope you learnt how to develop the ASP.NET Core MVC Web Application from the accompanying step-by-step tutorial.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Model Binders for ASP.NET MVC with Examples

clock September 15, 2023 06:57 by author Peter

ASP.NET MVC (Model-View-Controller) is a popular web development framework for creating strong and maintainable web applications. Model Binders are an important part of it. Model Binders play a critical role in mapping incoming HTTP requests to action method parameters, making it easier to work with client-side data. In this blog post, we will delve into the world of ASP.NET MVC Model Binders and present practical examples of how to use them.

What Exactly Are Model Binders?
Model Binders are ASP.NET MVC components that are responsible for mapping data from numerous sources, such as form fields, query strings, route parameters, and JSON payloads, to action method parameters. They are critical in easing the process of taking user input and transforming it into highly typed objects that your program may use.

Here's a detailed breakdown of how Model Binders work:

  • A user delivers an HTTP request to your ASP.NET MVC application, generally via a form submission or an API call.
  • Routing: The MVC framework uses routing rules to identify which controller and action method should handle the request.
  • Model Binders are useful in this situation. They collect data from the HTTP request and transfer it to the action method's arguments. The mapping is based on the names and types of parameters.
  • Execution of Action Methods: After the data is bound to the action method parameters, the method is executed using the provided data.
  • The action method processes the data and provides a response, which is returned to the client.

Now, let's look at some real-world examples of Model Binders.

Binding to Simple Types as an Example
Assume you have a simple HTML form with a single text input field named "username." You wish to capture the user's entered username.
public ActionResult Register(string username)
{
    // Process the username
    return View();
}

In this scenario, the Model Binder automatically binds the username parameter based on the name of the form input field.

Example 2: Complex Type Binding
Model Binders can also be used to tie complex types, such as custom classes, to action method parameters. Consider the following User class:

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}


You can bind an instance of the User class from a form submission as follows:
public ActionResult CreateUser(User user)
{
    // Process the user object
    return View();
}

The Model Binder will automatically populate the User object's properties using the submitted form data.
Example 3. Custom Model Binders

In some cases, you might need to implement custom Model Binders to handle complex scenarios. For example, if you want to bind data from a non-standard source or perform custom data transformation, you can create a custom Model Binder.
public class CustomBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // Custom logic to bind the model
        // Example: Read data from a cookie and populate the model
    }
}


To use the custom Model Binder, you can decorate your action method parameter with the [ModelBinder] attribute:

public ActionResult MyAction([ModelBinder(typeof(CustomBinder))] MyModel model)
{
    // Custom binding logic applied
    return View();
}

ASP.NET MVC Model Binders are critical components that let you manage user input data in your online applications. They make it simple to convert HTTP request data to action method parameters, making it easier to work with user-supplied data. Model Binders provide a strong technique for streamlining data binding in your ASP.NET MVC applications, whether you're dealing with simple types or complex objects.

You can design more efficient and maintainable web apps with ASP.NET MVC if you understand how Model Binders function and use them effectively.



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.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 :: 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.



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