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



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.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Using Auto-Mapper In An ASP.NET Core MVC Application

clock August 25, 2020 08:24 by author Peter

In today’s article we will look at an extremely useful feature. In many applications, the data we collect on the user interface needs to be converted to some different form before it can be stored in the data store and vice versa. This requires some mapping logic and it is mostly done using mapping classes and logic. Today, we will look at a ready to use Nuget package to do this mapping for us and make the process amazingly simple. We will apply this mapping in an ASP.NET Core MVC application.

Creating the .NET Core MVC application
We will start by creating an ASP.NET Core 3.1 MVC application using Visual Studio 2019 community edition as below,

We select the ASP.NET Core web application and click “Next”

Next, we enter the project details and click “Create”

From the list of ASP.NET Core web applications, we select “Web Application (Model-View-Controller) and leave all other values as default.
 
We now have the ASP.NET Core MVC application created. The next step is to add the “AutoMapper” Nugget package as below,

Remember to select the latest version.

After that create three classes under the “Models” folder as below,
 
Employee.cs

    namespace WebAppAutoMapper.Models { 
        publicclassEmployee { 
            publicstring FirstName { 
                get; 
                set; 
            } 
            publicstring LastName { 
                get; 
                set; 
            } 
            publicstring StreetAddress { 
                get; 
                set; 
            } 
            publicstring City { 
                get; 
                set; 
            } 
            publicstring Province { 
                get; 
                set; 
            } 
            publicstring Country { 
                get; 
                set; 
            } 
            publicstring Email { 
                get; 
                set; 
            } 
            publicstring Phone { 
                get; 
                set; 
            } 
            publicEmployee() { 
                FirstName = "Munib"; 
                LastName = "Butt"; 
                StreetAddress = "123 Street One"; 
                City = "Toronto"; 
                Province = "Ontario"; 
                Country = "Canada"; 
                Email = "[email protected]"; 
                Phone = "+14161112222"; 
            } 
        } 
    } 

EmployeeDTO.cs

    namespace WebAppAutoMapper.Models { 
        publicclassEmployeeDTO { 
            publicstring Name { 
                get; 
                set; 
            } 
            publicstring Address { 
                get; 
                set; 
            } 
            publicstring Email { 
                get; 
                set; 
            } 
            publicstring Phone { 
                get; 
                set; 
            } 
        } 
    } 

And finally,AutoMap.cs

    using AutoMapper; 
     
    namespace WebAppAutoMapper.Models 
    { 
    publicclassAutoMap : Profile 
        { 
    publicAutoMap() 
            { 
                CreateMap<Employee, EmployeeDTO>() // means you want to map from Employee to EmployeeDTO 
                .ForMember(d => d.Name, source => source.MapFrom(s => s.FirstName + " " + s.LastName)) 
                .ForMember(d => d.Address, source => source.MapFrom(s => s.StreetAddress + ", " + s.City + ", " + s.Province + ", " + s.Country)) 
                .ForMember(d => d.Phone, source => source.MapFrom(s => s.Phone)) 
                .ForMember(d => d.Email, source => source.MapFrom(s => s.Email)); 
            } 
        } 
    } 

Here we see that we have an Employee class which has several properties. We also have an EmployeeDTO class which has fewer properties than the Employee class. Now, we want to map the values from the Employee class to the EmployeeDTO class using some mapping logic. This logic is implemented in the AutoMap.cs class which inherits from the Profile class.
 
Finally, we setup the AutoMap in the Startup.cs class in the “ConfigureServices” function as below,

    using Microsoft.AspNetCore.Builder; 
    using Microsoft.AspNetCore.Hosting; 
    using Microsoft.Extensions.Configuration; 
    using Microsoft.Extensions.DependencyInjection; 
    using Microsoft.Extensions.Hosting; 
    using AutoMapper; 
    using WebAppAutoMapper.Models; 
     
    namespace WebAppAutoMapper 
    { 
    publicclassStartup 
        { 
    publicStartup(IConfiguration configuration) 
            { 
                Configuration = configuration; 
            } 
     
    public IConfiguration Configuration { get; } 
     
    // This method gets called by the runtime. Use this method to add services to the container. 
    publicvoid ConfigureServices(IServiceCollection services) 
            { 
                services.AddAutoMapper(c => c.AddProfile<AutoMap>(), typeof(Startup)); 
                services.AddControllersWithViews(); 
            } 
     
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    publicvoid Configure(IApplicationBuilder app, IWebHostEnvironment env) 
            { 
    if (env.IsDevelopment()) 
                { 
                    app.UseDeveloperExceptionPage(); 
                } 
    else 
                { 
                    app.UseExceptionHandler("/Home/Error"); 
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 
                    app.UseHsts(); 
                } 
                app.UseHttpsRedirection(); 
                app.UseStaticFiles(); 
     
                app.UseRouting(); 
     
                app.UseAuthorization(); 
     
                app.UseEndpoints(endpoints => 
                { 
                    endpoints.MapControllerRoute( 
                        name: "default", 
                        pattern: "{controller=Home}/{action=Index}/{id?}"); 
                }); 
            } 
        } 
    } 

Now, all the plumbing is in place and we can use the mapping as below in the Home Controller,

    using System.Diagnostics; 
    using Microsoft.AspNetCore.Mvc; 
    using Microsoft.Extensions.Logging; 
    using WebAppAutoMapper.Models; 
    using AutoMapper; 
     
    namespace WebAppAutoMapper.Controllers 
    { 
    publicclassHomeController : Controller 
        { 
    privatereadonly ILogger<HomeController> _logger; 
    privatereadonly IMapper _mapper; 
     
    publicHomeController(ILogger<HomeController> logger, IMapper mapper) 
            { 
                _logger = logger; 
                _mapper = mapper; 
            } 
     
    public IActionResult Index() 
            { 
                Employee emp = new Employee(); 
    var empDTO = _mapper.Map<EmployeeDTO>(emp); 
    return View(); 
            } 
     
    public IActionResult Privacy() 
            { 
    return View(); 
            } 
     
            [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 
    public IActionResult Error() 
            { 
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); 
            } 
        } 
    } 

We can put a breakpoint at the “return View();” line in the Index function and see the Employee DTO values as below,

Here we see that the empDTO object has the values extracted and mapped from the Employee object.

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Handle Multiple Submit Buttons in ASP.NET MVC 6?

clock July 30, 2020 13:16 by author Peter

Today, let me explain you how to handle multiple submit buttons in ASP.NET MVC 6. Sometimes you will need to handle multiple submit buttons on a similar form as as in the following picture.

As you can see on the above picture, we've got the three buttons Login, Register and Cancel. Here every button has totally different functionality. in this way every submit button will post a form to the server but will provide totally different values of every button.

Make a controller with one action method that accepts other parameters, one is for the model and the other is for determining the status of the button click.
[HttpPost] 
public ActionResult Index(Login model, string command) 

if (command=="Login") 

// do stuff 
return RedirectToAction("Home"); 

else if (command=="Register") 

// do stuff 
ViewBag.msg = "You have Clicked Register button"; 
return View(); 


else if (command=="Cancel") 

// do stuff 
ViewBag.msg = "You have Clicked Cancel Button"; 
return View(); 

else 

return View(); 



In the preceding code snippet, assume you clicked on the Login button, then the command parameter can have the values Login, null, null respectively. Create a View for the preceding controller.
@model MvcMultipleSubmitButtons.Models.Login 
@{ 
ViewBag.Title = "Index"; 

<h2> 
Handling multiple submit buttons in MVC </h2> 
<h5 style="color: Red">@ViewBag.msg</h5> 
<form action="Home/Index" id="myform" method="post" >  
//here action name is Index, controller name is Home. So the action path is Home/Index 
<table> 
<tr> 
<td> 
UserName 
</td> 
<td> 

</td> 
<td>@Html.TextBoxFor(m => m.userName) 
</td> 
<td> 
@Html.ValidationMessageFor(m => m.userName) 
</td> 
</tr> 
<tr> 
<td> 
Password 
</td> 
<td> 

</td> 
<td>@Html.TextBoxFor(m => m.password) 
</td> 
<td> 
@Html.ValidationMessageFor(m => m.password) 
</td> 
</tr> 
</table> 
<br/> 

<div style="padding-left: 80px;"> 
<input type="submit" id="Login" value="Login" name="Command" title="Login" /> 
<input type="submit" id="Register" value="Register" name="Command" title="Register" /> 
<input type="submit" value="Cancel" name="Command" title="Cancel" /> 

</div> 
</form> 


You can declare the form tag in another way as within the following:
@using(Html.BeginForm("Index","Home",FormMethod.Post)) 
{  
//here action name is Index, controller name is Home and form method is post. 
}


Note: there's a relation between button name and action method parameter. for instance, the button name is “Command”, the action parameter name ought to be “command”.

You can have different names for each button. So in that case you need to handle it as in the following:
<input type="submit" id="Login" value="Login" name="Command1" title="Login" /> 
<input type="submit" id="Register" value="Register" name="Command2" title="Register" /> 
<input type="submit" value="Cancel" name="Command3" title="Cancel" /> 


Controller
public ActionResult Index(Login model, string command1, string command2, string command3) 

   // here command1 is for Login, command2 is for Register and command3 is for cancel 


Create a Model class with the name Login.
public class Login 

    public string userName { get; set; } 
    public string password { get; set; } 

I hope it helps for you!

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting UK - HostForLIFE.eu :: How to Delete Multiple Items in ASP.NET with JSON?

clock June 26, 2020 13:15 by author Peter

Today, I want to show you how to delete multiple Items in ASP.NET with JSON. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. Now, open your project and write the following code:

View
<table class="table"> 
@foreach (var role in Model) { 
<tr> 
    <td> 
        <input id="responsable1" name="checkResp" value="@role.id" type="checkbox" /> 
        <strong>@role.Name</strong> 
    </td> 
</tr> 

</table> 
<input id="DeleteBtn" type="button" value="Delete Selected" /> 
<script> 
$("#DeleteBtn").on("click", function() { 
    var boxData = []; 
    $("input[name='checkResp']:checked").each(function() { 
        boxData.push($(this).val()); 
    }); 
    $.ajax({ 
        url: '/Roles/DeleteMultiple', 
        data: { 
            RoleId: boxData.join(",") 
        }, 
        cache: false, 
        type: "POST", 
        timeout: 10000, 
        dataType: "json", 
        success: function(result) { 
            window.location.reload(); 
        } 
    }); 
}); 
</script> 


Controller
[HttpPost] 
public JsonResult DeleteMultiple(string RoleId) { 
ApplicationDbContext db = new ApplicationDbContext(); 
var RoleIds = RoleId.Split(','); 
foreach(var id in RoleIds) { 
    int idConverted = Convert.ToInt32(id); 
    Roles roleid = db.Roles.Find(idConverted); 
    db.Roles.Remove(roleid); 

context.SaveChanges(); 
var message = "Selected roles have been deleted"; 
return Json(message); 


DeleteMultiple - Action Name
Roles - Controller Name

 

HostForLIFE.eu ASP.NET MVC 6 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: HTML Helpers In ASP.NET MVC

clock April 9, 2020 05:10 by author Peter

What is an Html Helper?
Html helper is a method that is used to render HTML content in a view. Html helpers are implemented using an extension method. If you want to create an input text box with

id=email and name in email:
  <input type=text id=email name=email value=’’/> 


This is all the Html we need to write -- by using the helper method it becomes so easy:
  @Html.TextBox(‘email’) 

It will generate a textbox control whose name is the email.

If we want to assign the value of the textbox with some initial value then use the below method:
  @Html.TextBox(‘email’,’[email protected]’) 

If I want to set an initial style for textbox we can achieve this by using the below way:
  @Html.TextBox(‘email’,’[email protected]’,new {style=’your style here’ , title=’your title here’});  

Here the style we pass is an anonymous type.

If we have a reserved keyword like class readonly and we want to use this as an attribute  we will do this using the below method, which means append with @ symbol with the reserved word.
  @Html.TextBox(‘email’,’[email protected]’,new {@class=’class name’, @readonly=true}); 

If we want to generate label:
  @Html.Label(‘firstname’,’sagar’) 

For password use the below Html helper method to create password box:
  @Html.Password(“password”) 

If I want to generate a textarea then for this also we have a method:
  @Html.TextArea(“comments”,”,4,12,null)  

In the above code 4 is the number of rows and 12 is the number of columns.

To generate a hidden box:
  @Html.Hidden(“EmpID”) 

Hidden textboxes are not displayed on the web page but used for storing data and when we need to pass data to action method then we can use that.

Is it possible to create our Html helpers in asp.net MVC?

Yes, we can create our Html helpers in MVC.

Is it mandatory to use Html helpers?

No, we can use plain Html for that but Html helpers reduce a significant amount of Html code to write that view.
Also, your code is simple and maintainable and if you require some complicated logic to generate view then this is also possible.



ASP.NET MVC Hosting - HostForLIFE.eu :: Dynamic am-Charts In ASP.NET MVC

clock July 30, 2019 12:17 by author Peter

Here, we will learn about creating dynamic am-charts in ASP.NET MVC 5. Charts are very useful for seeing how much work is done in any place in a short period of time.

Prerequisites

  • Basic knowledge of jQuery.
  • Data from which we can generate the charts.

Create a new project in ASP.NET MVC
We are going to use the following jQuery libraries provided by amCharts.
<script src="https://www.amcharts.com/lib/4/core.js"></script>    
<script src="https://www.amcharts.com/lib/4/charts.js"></script>     
<script src="https://www.amcharts.com/lib/4/plugins/forceDirected.js"></script>    
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script> 
    

We are going to use the dummy API for the chart data.
https://api.myjson.com/bins/zg8of

Open the View -> Home -> Index.cshtml and write the code for generating the chart.
@{    
ViewBag.Title = "AM Chart Demo";    
}    

<div id="chartData"></div>    

@Scripts.Render("~/bundles/jquery")    

<script src="https://www.amcharts.com/lib/4/core.js"></script>    
<script src="https://www.amcharts.com/lib/4/charts.js"></script>    
<script src="https://www.amcharts.com/lib/4/plugins/forceDirected.js"></script>    
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>    

<script>    
$(document).ready(function () {    
$.ajax({    
    url: 'https://api.myjson.com/bins/zg8of',    
    method: 'GET', success: function (data) {    
        generateChart(data);    
    }, error: function (err) {    
        alert("Unable to display chart. Something went wrong.");    
    }    
});    

function generateChart(data, iteration = 0) {    
    var dates = [];    
    var newData = [];    
    var gr = [];    

    function groupBy(array, f) {    
        var groups = {};    
        array.forEach(function (o) {    
            var group = JSON.stringify(f(o));    
            groups[group] = groups[group] || [];    
            groups[group].push(o);    
        });    
        return Object.keys(groups).map(function (group) {    
            return groups[group];    
        })    
    }    
    var result = groupBy(data, function (item) {    
        return ([item.Name]);    
    });    
    $.each(result, function (a, b) {    
        var d1 = b.map(function (i) {    
            return i.Month;    
        });    
        $.extend(true, dates, d1);    
    });    
    $.each(dates, function (a, b) {    
        var item = {    
            sales_figure: b    
        };    
        $.each(result, function (i, c) {    
            el = c.filter(function (e) {    
                return e.Month == b;    
            });    
            if (el && el.length > 0) {    
                item[c[i].Name.toUpperCase()] = el[0].Sales_Figure;    
                if (gr.filter(function (g) {    
                    return g == c[i].Name.toUpperCase();    
                }).length <= 0) {    
                    gr.push(c[i].Name.toUpperCase());    
                }    
            }    
        });    
        if (Object.keys(item).length > 1) newData.push(item);    
    });    
    $chartData = $('#chartData');    
    var am_el = $('<div id="dc-' + iteration + '" class="col-md-12 col-xs-12 card-item">');    
    am_el.append($('<div class="lgnd col-md-12 col-xs-12 bb2"><div id="l-' + iteration + '" class="col-md-12 col-xs-12"></div></div>'));    
    am_el.append($('<div id="c-' + iteration + '" class="col-md-12 col-xs-12" style="min-height:250px ; margin-left: -8px;">'));    
    $chartData.html(am_el);    
    var chart = am4core.create("c-" + iteration, am4charts.XYChart);    
    am4core.options.minPolylineStep = Math.ceil(newData.length / 50);    
    am4core.options.commercialLicense = true;    
    am4core.animationDuration = 0;    
    chart.data = newData;    
    var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());    
    categoryAxis.dataFields.category = "sales_figure";    
    categoryAxis.renderer.minGridDistance = 70;    
    categoryAxis.fontSize = 12;    
    var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());    
    valueAxis.fontSize = 12;    
    valueAxis.title.text = "Sales Figure";    
    chart.legend = new am4charts.Legend();    
    chart.legend.position = "top";    
    chart.legend.fontSize = 12;    
    var markerTemplate = chart.legend.markers.template;    
    markerTemplate.width = 10;    
    markerTemplate.height = 10;    
    var legendContainer = am4core.create("l-" + iteration, am4core.Container);    
    legendContainer.width = am4core.percent(100);    
    chart.legend.parent = legendContainer;    
    var legendDiv = document.getElementById("l-" + iteration);    

    function resizeLegendDiv() {    
        legendDiv.style.height = chart.legend.measuredHeight + "px";    
        legendDiv.style.overflow = "hidden";    
    }    
    chart.legend.events.on('inited', resizeLegendDiv);    
    chart.colors.list = [am4core.color("#0D8ECF"), am4core.color("#FF6600"), am4core.color("#FCD202"), am4core.color("#B0DE09"), am4core.color("#2A0CD0"), am4core.color("#CD0D74"), am4core.color("#CC0000"), am4core.color("#00CC00"), am4core.color('#ffd8b1'), am4core.color("#990000"), am4core.color('#4363d8'), am4core.color('#e6194b'), am4core.color('#3cb44b'), am4core.color('#ffe119'), am4core.color('#f58231'), am4core.color('#911eb4'), am4core.color('#46f0f0'), am4core.color('#f032e6'), am4core.color('#bcf60c'), am4core.color('#fabebe'), am4core.color('#008080'), am4core.color('#e6beff'), am4core.color('#9a6324'), am4core.color('#fffac8'), am4core.color('#800000'), am4core.color('#aaffc3'), am4core.color('#808000'), am4core.color('#ffd8b1'), am4core.color('#000075')] $.each(gr, function (l, d) {    
        var series = chart.series.push(new am4charts.LineSeries());    
        series.dataFields.valueY = d;    
        series.name = d;    
        series.dataFields.categoryX = "sales_figure";    
        series.tooltipText = "{name}: [bold]{valueY}[/]";    
        series.strokeWidth = 2;    
        series.minBulletDistance = 30;    
        series.tensionX = 0.7;    
        series.legendSettings.labelText = "[bold]" + "{name}";    
        var bullet = series.bullets.push(new am4charts.CircleBullet());    
        bullet.circle.strokeWidth = 2;    
        bullet.circle.radius = 3;    
        bullet.circle.fill = am4core.color("#fff");    
        var bulletbullethover = bullet.states.create("hover");    
        bullethover.properties.scale = 1.2;    
        chart.cursor = new am4charts.XYCursor();    
        chart.cursor.behavior = "panXY";    
        chart.cursor.snapToSeries = series;    
    });    
    chart.scrollbarX = new am4core.Scrollbar();    
    chartchart.scrollbarX.parent = chart.bottomAxesContainer;    
}    

});    
</script>  
 

Output

 

 



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