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 :: How to Extend ASP.NET MVC AuthorizeAttribute?

clock August 24, 2018 11:17 by author Peter

Today, I will show you how to Extend ASP.NET MVC AuthorizeAttribute and how to Unit Test with ControllerActionInvoker. The reason for extending the AuthorizeAttribute class is that we might decide to store user credential information in a variety of differently data sources such as Active Directory, a database, an encrypted text file, etc…Or we might add custom logic to authorize a user.

OK, now we have set up our premises, let’s dive straight into the code for the subclass of AuthorizeAttribute:
    namespace SecurityDemo.Classes 
    { 
        [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] 
        public class CustomAuthorizeAttribute: AuthorizeAttribute 
        { 
            public override voidOnAuthorization(AuthorizationContextfilterContext) 
            { 
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
                //the user is not allowed to execute the Action. An Unauthorized result is raised. 
                filterContext.Result = newHttpUnauthorizedResult(); 
                var roles = GetAuthorizedRoles(); 
                stringwindowLoginName = filterContext.HttpContext.User.Identity.Name; 
                //windowLoginName and ADGroup is expected to have this format "ABC\\XYZ" 
                stringdomainName = windowLoginName.Contains(@ "\") ?windowLoginName.Substring(0, windowLoginName.IndexOf(@"\ 
                ", System.StringComparison.OrdinalIgnoreCase)) : windowLoginName; 
                windowLoginName = windowLoginName.Contains(@ "\") ? windowLoginName.Substring(windowLoginName.LastIndexOf(@ "\", System.StringComparison.OrdinalIgnoreCase) + 1): windowLoginName; boolisValidUser = false; 
                if (roles.Any(role => ADClass.IsUserInADGroup(windowLoginName, role.Substring(role.LastIndexOf(@ "\", System.StringComparison.OrdinalIgnoreCase) + 1), domainName))) //if window login belongs to AD group from config 
                { 
                    isValidUser = true; 
                } 
                elseif (roles.Any(role => windowLoginName.ToLower().Equals(role.Substring(role.LastIndexOf(@ "\", System.StringComparison.OrdinalIgnoreCase) + 1).ToLower()))) //if window login belongs to a user from config 
                { 
                    isValidUser = true; 
                } 
                if (isValidUser) 
                { 
                    return; 
                } 
                else 
                { 
                    HandleUnauthorizedRequest(filterContext); 
                } 
            } 
            protected override void HandleUnauthorizedRequest(AuthorizationContextfilterContext) 
            { 
                filterContext.Result = newViewResult 
                { 
                    ViewName = "~/Views/Shared/UnAuthorized.cshtml" 
                }; 
            } 
            //get list of authorized Active Directory groups and windows users from 
            // web.config 
            privateIEnumerable < string > GetAuthorizedRoles() 
            { 
                var appSettings = ConfigurationManager.AppSettings[this.Roles]; 
                if (string.IsNullOrEmpty(appSettings)) 
                { 
                    return new[] 
                    { 
                        "" 
                    }; 
                } 
                IEnumerable < string > rolesEnumerable = appSettings.Split(',').Select(s => s.Trim()); 
                return rolesEnumerable; 
            } 
        } 
    } 

 
In the sublassCustomAuthorizeAttribute above we override the OnAuthorization(Authorization Context filterContext) method and provide the logic to identify the windows login user, check the person against the list of authorized Active Directory groups and Windows users from web.config. We also override against the HandleUnauthorizedRequest(AuthorizationContextfilterContext) method to return a view for access denied. Of course, as mentioned, the authorization logic can be made as flexible and complex as possible according to specific business needs.

To use the extended attribute in a controller, we just apply to attribute to a method or class as in the below code snippet:
    public class ProductController: Controller 
    { 
        [CustomAuthorize(Roles = SystemRole.Administrators)] 
        public ActionResultIndex() 
        { 
            return View("Index"); 
        } 
        [CustomAuthorize(Roles = SystemRole.Administrators)] 
        public ActionResultDetails(int Id) 
        { 
            return View("Details"); 
        } 
    } 
    // a helper class to define roles 
    public class SystemRole 
    { 
        public const string Administrators = "Administrators"; 
        public cons tstring Sales = "Sales"; 
    } 

There we have it, we have come up with how to implement custom security as an attribute to be applied to a controller.

Unit Testing:
We can simply test our new security feature by launching the web application through the web browser after providing the access list in the web.config as mentioned in the beginning of the article. There is nothing wrong with that. However, if we need to get more fancy and methodical by doing some full unit testing using NUnit or Microsoft UnitTestFramework (which I’ll be using in this article) then there are a few challenges we’ll be facing. First is we’ll need to simulate a browser session with a full HttpContext with widows login, session, etc… and the way to do it is to use Mock object. The second challenge is how to invoke the action methods of a controller with our CustomAuthorizeAttribute applied. The way to do it is to extend a class calledControllerActionInvoker and override a method called InvokeActionResult(). Also if you need to invoke an action method with router parameters you also need to override the GetParameterValues() method as well. Well, one picture is worth a thousand words, so I present to you a “picture” of all the code (words) involved for the unit test:
    namespace UnitTestSecurityDemo 
    { 
        public class ActionInvokerExpecter < TResult > : ControllerActionInvokerwhereTResult: ActionResult 
        { 
            public boolIsUnAuthorized = false; 
            ///<summary> 
            /// override to get ViewName of controller in action 
            ///</summary> 
            ///<param name="controllerContext"></param> 
            ///<param name="actionResult"></param> 
            protected override voidInvokeActionResult(ControllerContextcontrollerContext, ActionResultactionResult) 
                { 
                    string viewName = ((System.Web.Mvc.ViewResult) actionResult).ViewName; 
                    IsUnAuthorized = viewName.ToLower().Contains("unauthorized"); 
                } 
                ///// <summary> 
                ///// override to get Routedata of controller in action 
                ///// </summary> 
                ///// <param name="controllerContext"></param> 
                ///// <param name="actionDescriptor"></param> 
                ///// <returns></returns> 
            protected overrideIDictionary < string, object > GetParameterValues(ControllerContextcontrollerContext, ActionDescriptoractionDescriptor) 
            { 
                return controllerContext.RouteData.Values; 
            } 
        } 
    } 
    namespace UnitTestSecurityDemo 
    { 
        [TestClass] 
        public class UnitTest1 
        { 
            [TestMethod] 
            public void TestIndexView() 
            { 
                var controller = new ProductController(); 
                MockAuthenticatedControllerContext(controller, @ "abc\jolndoe"); 
                ConfigurationManager.AppSettings.Set("Administrators", @ "abc\Group-ABC-App, abc\jolndoe1"); 
                ActionInvokerExpecter < ViewResult > a = newActionInvokerExpecter < ViewResult > (); 
                a.InvokeAction(controller.ControllerContext, "Index"); 
                Assert.IsTrue(a.IsUnAuthorized); 
            } 
            [TestMethod] 
            public void TestDetailsView() 
            { 
                //since the Details() action method of the controller has a router parameter, we need to pass 
                //router data in as below 
                var controller = newProductController(); 
                varrouteData = newRouteData(); 
                routeData.Values.Add("id", 3); 
                MockAuthenticatedControllerContextWithRouteData(controller, @ "abc\jolndoe", routeData); 
                ConfigurationManager.AppSettings.Set("Administrators", @ "abc\Group-ABC-App, abc\jolndoe"); 
                ActionInvokerExpecter < ViewResult > a = newActionInvokerExpecter < ViewResult > (); 
                a.InvokeAction(controller.ControllerContext, "Details"); 
                Assert.IsTrue(a.IsUnAuthorized); 
            } 
            private static void MockAuthenticatedControllerContext(ProductController controller, stringuserName) 
            { 
                HttpContextBasehttpContext = FakeAuthenticatedHttpContext(userName); 
                ControllerContext context = newControllerContext(newRequestContext(httpContext, newRouteData()), controller); 
                controller.ControllerContext = context; 
            } 
            private static void MockAuthenticatedControllerContextWithRouteData(ProductController controller, stringuserName, RouteDatarouteData) 
            { 
                HttpContextBasehttpContext = FakeAuthenticatedHttpContext(userName); 
                ControllerContext context = newControllerContext(newRequestContext(httpContext, routeData), controller); 
                controller.ControllerContext = context; 
            } 
            public static HttpContextBaseFakeAuthenticatedHttpContext(string username) 
            { 
                Mock < HttpContextBase > context = newMock < HttpContextBase > (); 
                Mock < HttpRequestBase > request = newMock < HttpRequestBase > (); 
                Mock < HttpResponseBase > response = newMock < HttpResponseBase > (); 
                Mock < HttpSessionStateBase > session = newMock < HttpSessionStateBase > (); 
                Mock < HttpServerUtilityBase > server = newMock < HttpServerUtilityBase > (); 
                Mock < IPrincipal > user = newMock < IPrincipal > (); 
                Mock < IIdentity > identity = newMock < IIdentity > (); 
                context.Setup(ctx => ctx.Request).Returns(request.Object); 
                context.Setup(ctx => ctx.Response).Returns(response.Object); 
                context.Setup(ctx => ctx.Session).Returns(session.Object); 
                context.Setup(ctx => ctx.Server).Returns(server.Object); 
                context.Setup(ctx => ctx.User).Returns(user.Object); 
                user.Setup(ctx => ctx.Identity).Returns(identity.Object); 
                identity.Setup(id => id.IsAuthenticated).Returns(true); 
                identity.Setup(id => id.Name).Returns(username); 
                returncontext.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 :: Using HttpContext Outside An MVC Controller In .Net Core 2.1

clock August 21, 2018 11:24 by author Peter

Last Friday, while working on a web application based on ASP.Net Core 2.1, I came across a scenario where I had to put some data into memory. While that's not a problem, the catch is that the data has to be unique for each HTTP Session. Consider it as keeping a key that is to be used across different views to display some information related to that particular session.

The only possible solution satisfying my needs was to keep the "key" in session. However, the last point in the code that has access to the key is a simple helper class and not an MVC Controller. And we had no intentions to expose the "key" to our controller. So, the question remains: how do we save the key in session without exposing it to the controller?

Sample Code
In the following code, we have a very basic MVC application with our HomeController. We also have a RequestHandler that takes care of all the background logic making our controller clean and light.

using HttpContextProject.Helpers; 
using HttpContextProject.Models; 
using Microsoft.AspNetCore.Mvc; 
using System.Diagnostics; 
 
namespace HttpContextProject.Controllers 

    public class HomeController : Controller 
    { 
        public IActionResult Index() 
        { 
            return View(); 
        } 
 
        public IActionResult About() 
        { 
            // handle the request and do something 
            var requestHandler = new RequestHandler(); 
            requestHandler.HandleAboutRequest(); 
 
            ViewData["Message"] = "This is our default message for About Page!"; 
            return View(); 
        } 
    } 

 
 
namespace HttpContextProject.Helpers 

    public class RequestHandler 
    { 
        internal void HandleAboutRequest() 
        { 
            // do something here 
        } 
    } 


As it can be seen in the above code, we are simply setting a message in the ViewData and rendering it on the view. Nothing fancy so far. Now, let's see how we can set our message in Http Session from RequestHandler and later access it inside the controller.

Using HttpContext in a Helper Class

With .Net Core 2.1 we can not access the HttpContext outside a controller, however, we can use the IHttpContextAccessor to access the current session outside a controller. In order to do so, we need to add the Session and HttpContextAccessor middle-ware to ConfigureServices method of our Startup class as shown in the code below,

using HttpContextProject.Helpers; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.AspNetCore.Http; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.DependencyInjection; 
 
namespace HttpContextProject 

    public class Startup 
    { 
        public IConfiguration Configuration { get; } 
        public Startup(IConfiguration configuration) 
        { 
            Configuration = configuration; 
        }        
 
        public void ConfigureServices(IServiceCollection services) 
        { 
            services.Configure<CookiePolicyOptions>(options => { 
                options.CheckConsentNeeded = context => true; 
                options.MinimumSameSitePolicy = SameSiteMode.None; 
            }); 
            services.AddSession(); 
            services.AddSingleton<RequestHandler>(); 
            services.AddHttpContextAccessor(); 
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 
        } 
 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
        { 
            if (env.IsDevelopment()) { 
                app.UseDeveloperExceptionPage(); 
            } 
            else { 
                app.UseExceptionHandler("/Home/Error"); 
            } 
            app.UseSession(); 
            app.UseMvc(routes => { 
                routes.MapRoute( 
                    name: "default", 
                    template: "{controller=Home}/{action=Index}/{id?}"); 
            }); 
        } 
    } 


The next thing we need to do is to add a dependency of IHttpContextAccessor in the RequestHandler. This allows us to access the HttpContext inside the request handler. After we have done required processing for the request, we can now set the message in session, using the Session.SetString(key, value) method. Please refer to the code below,

using Microsoft.AspNetCore.Http; 
 
namespace HttpContextProject.Helpers 

    public class RequestHandler 
    { 
        IHttpContextAccessor _httpContextAccessor; 
        public RequestHandler(IHttpContextAccessor httpContextAccessor) 
        { 
            _httpContextAccessor = httpContextAccessor; 
        } 
 
        internal void HandleAboutRequest() 
        { 
            // handle the request 
            var message = "The HttpContextAccessor seems to be working!!"; 
            _httpContextAccessor.HttpContext.Session.SetString("message", message); 
        } 
    } 


Now, that we have our RequestHandler all set, it's time to make some changes in the HomeController. Currently, the "new" RequestHandler  is inside the action method, which is not a good practice. So, I will decouple the handler from the controller and rather inject it as a dependency in the constructor. Next thing we do is to set the message in ViewData from the session, as shown in the code below,

using HttpContextProject.Helpers; 
using HttpContextProject.Models; 
using Microsoft.AspNetCore.Mvc; 
using System.Diagnostics; 
 
namespace HttpContextProject.Controllers 

    public class HomeController : Controller 
    { 
        private readonly RequestHandler _requestHandler; 
 
        public HomeController(RequestHandler requestHandler) 
        { 
            _requestHandler = requestHandler; 
        } 
 
        public IActionResult About() 
        { 
            _requestHandler.HandleAboutRequest(); 
            ViewData["Message"] = HttpContext.Session.GetStringValue("message"); 
            return View(); 
        } 
    } 


Note that I'm using Sesseion.GetStringValue(key) which is an extension method that I have added to retrieve data from the session, however, it's not really required. You can simply use the Session.TryGetValue(key, value) as well.

In case you have not figured it out already, I must tell you that we need to register our RequestHandler in the ConfigureServices method of the Startup class so that the dependency for our controller can be resolved.

Summary
With the above changes in place, we can now access the HttpContext.Session inside our request handler and the same can be done for any other class as well. However, there is one thing that I don't like about this approach. For every single component where we need to access the session, we have to inject a dependency of IHttpContextAccessor.

While for one or two components it's not a problem, it can be very daunting if we have to do the same over and over again. There is a way to achieve the same accessibility without having to inject any dependency, but that's a story for another day and I will write about that in my next post.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Charts In ASP.NET MVC Using Chart.js

clock August 10, 2018 11:36 by author Peter

This article demonstrates how to create charts in ASP.NET MVC using Chart.js and C#. This article starts with how to use Chart.js in your MVC project. After that, it demonstrates how to add charts to a View.

Using Chart.js in your ASP.NET MVC project (C#)

Chart.js is a JavaScript charting tool for web developers. The latest version can be downloaded from GitHub or can use CDN.

In this article, Chart.js CDN (v2.6.0) is used for demonstration purposes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script> 

In the View (*.cshtml), add the Chart.js CDN along with jQuery CDN (recommended) in the head section if you haven’t mentioned those in layout pages.
@section head 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" type="text/javascript"></script> 
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 


Adding chart to a View
In the following example, the <canvas> tag is used to hold the chart in View’s <body> section.
<div Style="font-family: Corbel; font-size: small ;text-align:center " class="row"> 
    <div  style="width:100%;height:100%"> 
            <canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas> 
    </div> 
</div> 

Now, in the Controller class, let’s add a method to return the data for the chart that we added in the View. In this example, we are using JSON format for the source data.
[HttpPost] 
public JsonResult NewChart() 

    List<object> iData = new List<object>(); 
    //Creating sample data 
    DataTable dt = new DataTable() ; 
    dt.Columns.Add("Employee",System.Type.GetType("System.String")); 
    dt.Columns.Add("Credit",System.Type.GetType("System.Int32")); 
 
    DataRow dr = dt.NewRow(); 
    dr["Employee"] = "Sam"; 
    dr["Credit"] = 123; 
    dt.Rows.Add(dr); 
 
    dr = dt.NewRow(); 
    dr["Employee"] = "Alex"; 
    dr["Credit"] = 456; 
    dt.Rows.Add(dr); 
 
    dr = dt.NewRow(); 
    dr["Employee"] = "Michael"; 
    dr["Credit"] = 587; 
    dt.Rows.Add(dr); 
    //Looping and extracting each DataColumn to List<Object> 
    foreach (DataColumn dc in dt.Columns) 
    { 
        List<object> x = new List<object>(); 
        x = (from DataRow drr in dt.Rows select drr[dc.ColumnName]).ToList(); 
        iData.Add(x); 
    } 
    //Source data returned as JSON 
    return Json(iData, JsonRequestBehavior.AllowGet); 


The data from the source table is processed in such a way that each column in the result table is made to separate list. The first column is expected to have the X-axis data of the chart, whereas the consequent columns hold the data for Y-axis. (Chart.js expects the Axis labels in separate list. Please check the AJAX call section.)

The data for axises is combined to a single List<Object>, and returned from the method as JSON.

AJAX calls are used in the <script> section of View to call the method in Controller to get the chart data.
<script> 
    $.ajax({ 
        type: "POST", 
        url: "/Chart/NewChart", 
        contentType: "application/json; charset=utf-8", 
        dataType: "json", 
        success: function (chData) { 
        var aData = chData; 
        var aLabels = aData[0]; 
        var aDatasets1 = aData[1]; 
        var dataT = { 
            labels: aLabels, 
            datasets: [{ 
                label: "Test Data", 
                data: aDatasets1, 
                fill: false, 
                backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"], 
                borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"], 
                borderWidth: 1 
                }] 
            }; 
        var ctx = $("#myChart").get(0).getContext("2d"); 
        var myNewChart = new Chart(ctx, { 
            type: 'bar', 
            data: dataT, 
            options: { 
                responsive: true, 
                title: { display: true, text: 'CHART.JS DEMO CHART' }, 
                legend: { position: 'bottom' }, 
                scales: { 
                xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }], 
                yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }] 
            }, 
        } 
        }); 
    } 
}); 
</script> 


aData[0] has the data for X-Axis labels and aData[1] has the data for Y-Axis correspondingly.

As in the code, the AJAX call is made to the Controller method ’/Chart/NewChart’ where ‘Chart’ is the name of the Controller class and ‘NewChart’ is the method which returns the source data for the chart in JSON format.

AJAX call, when returned successfully, processes the returned JSON data.
The JSON data is processed to extract the labels and axis data for the chart preparation. The 2D context of the canvas ‘myChart’ is created using ‘getContext("2d")’ method, and then the context is used to create the chart object in ‘new Chart()’ method inside the script.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: ASP.NET Core 2.0 MVC View Components

clock August 7, 2018 09:51 by author Peter

How to reuse parts of web pages using View Components in ASP.NET Core MVC.

Solution
In an empty project, update Startup class to add services and middleware for MVC.
public void ConfigureServices( 
IServiceCollection services) 

services.AddScoped<IAddressFormatter, AddressFormatter>(); 
services.AddMvc(); 


public void Configure( 
IApplicationBuilder app, 
IHostingEnvironment env) 

app.UseMvc(routes => 

routes.MapRoute( 
    name: "default", 
    template: "{controller=Home}/{action=Index}/{id?}"); 
}); 


Add a Model to display in the View.
public class EmployeeViewModel 

public int Id { get; set; } 
public string Firstname { get; set; } 
public string Surname { get; set; } 


Add a Controller with action method returning ViewResult.
public IActionResult Index() 

var model = new EmployeeViewModel 

   Id = 1, 
   Firstname = "James", 
   Surname = "Bond" 
}; 
return View(model); 


Add a parent View named Index.cshtml.
@using Fiver.Mvc.ViewComponents.Models.Home 
@model EmployeeViewModel 

<div style="border: 1px solid black; margin: 5px"> 
<strong>Employee Details (view)</strong> 

<p>Id: @Model.Id</p> 
<p>Firstname: @Model.Firstname</p> 
<p>Surname: @Model.Surname</p> 

@await Component.InvokeAsync("Address", new { employeeId = Model.Id }) 
</div> 

@await Component.InvokeAsync("UserInfo") 

Add a View Component’s Model.

public class AddressViewModel 

public int EmployeeId { get; set; } 
public string Line1 { get; set; } 
public string Line2 { get; set; } 
public string Line3 { get; set; } 
public string FormattedValue { get; set; } 


Add a View Component’s class.
[ViewComponent(Name = "Address")] 
public class AddressComponent : ViewComponent 

private readonly IAddressFormatter formatter; 

public AddressComponent(IAddressFormatter formatter) 

  this.formatter = formatter; 


public async Task InvokeAsync(int employeeId) 

  var model = new AddressViewModel 
  { 
      EmployeeId = employeeId, 
      Line1 = "Secret Location", 
      Line2 = "London", 
      Line3 = "UK" 
  }; 
  model.FormattedValue =  
      this.formatter.Format(model.Line1, model.Line2, model.Line3); 
  return View(model); 



Add a View Component’s View named as Default.cshtml.
@using Fiver.Mvc.ViewComponents.Models.Home 
@model AddressViewModel 

<div style="border: 1px dashed red; margin: 5px"> 
<strong>Address Details (view component in Views/Home)</strong> 

<p>Employee: @Model.EmployeeId</p> 
<p>Line1: @Model.Line1</p> 
<p>Line2: @Model.Line2</p> 
<p>Line3: @Model.Line3</p> 
<p>Full Address: @Model.FormattedValue</p> 
</div>

Discussion
View Components are special type of Views rendered inside other Views. They are useful for reusing parts of a View or splitting a large View into smaller components. Unlike Partial Views, View Components do not rely on Controllers. They have their own class to implement the logic to build component’s model and Razor View page to display HTML/CSS.

I like to think of them as mini-controllers, although this is not strictly correct but helps conceptualize their usage. Unlike Controllers, they do not handle HTTP requests or have Controller lifecycle, which means they can’t rely on filters or model binding.

View Components can utilize dependency injection, which makes them powerful and testable.

Creating
There are a few ways to create View Components. I’ll discuss the most commonly used (and best in my view) option.
1. Create a class (anywhere in your project) and inherit from ViewComponent abstract class.

  • Name of the class, by convention, ends with ViewComponent.

2. Create a method called InvokedAsync() that returns Task<IViewComponentResult>.

  • This method can take any number of parameters, which will be passed when invoking the component (see Invoking section below).

3. Create Model e.g. via database etc.
4. Call IViewComponentResult by calling the View() method of base ViewComponent. You could pass your model to this method.

  • Optionally you could specify the name of razor page (see Discovery section below).

The base ViewComponent class gives access to useful details (via properties) like HttpContext, RouteData, IUrlHelper, IPrincipal, and ViewData.

Invoking
View Components can be invoked by either,

  1. Calling @await Component.InvokeAsync(component, parameters) from the razor view.
  2. Returning ViewComponent(component, parameters) from a controller.

Here, “component” is a string value refereeing to the component class.
InvokeAsync() method can take any number of parameters and is passed using an anonymous object when invoking the View Component.

Below is an example of second option above. Notice that the second action method doesn’t work because the Razor page for the component is not under Controller’s Views folder,
public class ComponentsController : Controller 

public IActionResult UserInfo() 

 // works: this component's view is in Views/Shared 
 return ViewComponent("UserInfo"); 


public IActionResult Address() 

 // doesn't works: this component's view is NOT in Views/ 
 return ViewComponent("Address", new { employeeId = 5 }); 

}

Discovery
MVC will search for the razor page for View Component in the following sequence,
Views/[controller]/Components/[component]/[view].cshtml
Views/Shared/Components/[component]/[view].cshtml

Here matches either,
Name of the component class, minus the ViewComponent suffix if used.
Value specified in [ViewComponent] attribute applied to component class.

Also, [view] by default is Default.cshtml, however, it can be overwritten by returning a different name from the component class. Below the component returns a view named Info.cshtml,
public class UserInfoViewComponent : ViewComponent 

public async Task InvokeAsync() 

 var model = new UserInfoViewModel 
 { 
     Username = "[email protected]", 
     LastLogin = DateTime.Now.ToString() 
 }; 
 return View("info", model); 

}


jQuery
You could access View Components via jQuery as well. To do so enable the use of Static Files in Startup,
public void Configure( 
IApplicationBuilder app, 
IHostingEnvironment env) 

app.UseStaticFiles(); 
app.UseMvc(routes => 

  routes.MapRoute( 
      name: "default", 
      template: "{controller=Home}/{action=Index}/{id?}"); 
}); 


Add jQuery script file to wwwroot and use it in a page
<html> 
<head> 
<meta name="viewport" content="width=device-width" /> 
<title>ASP.NET Core View Components</title> 

<script src="~/js/jquery.min.js"></script> 

</head> 
<body> 
<div> 
<strong>ASP.NET Core View Components</strong> 

<input type="button" id="GetViewComponent" value="Get View Component" /> 

<div id="result"></div> 
</div> 
<script> 
$(function () { 
    $("#GetViewComponent").click(function () { 

        $.ajax({ 
            method: 'GET', 
            url: '@Url.Action("UserInfo", "Components")' 
        }).done(function (data, statusText, xhdr) { 
            $("#result").html(data); 
        }).fail(function (xhdr, statusText, errorText) { 
            $("#result").text(JSON.stringify(xhdr)); 
        }); 

    }); 
}); 
</script> 
</body> 
</html>



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Check Your ASP.NET MVC Version Installed In Your System Using Code During Runtime

clock August 3, 2018 11:17 by author Peter

Create an Application named MVC version

Look at an example for better reference i.e. RouteConfig.cs

Create A Controller named “Home” .

Add the code given below in HomeController.cs for better results, as expected.using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
namespace Mvc_Version.Controllers { 
    public class HomeController: Controller { 
        // 
        // GET: /Home/ 
        public string Version() { 
            return "<h2>The Installed Mvc Version In your System Is : " + typeof(Controller).Assembly.GetName().Version.ToString() + "</h2>"; 
        } 
    } 
}   

We mentioned the controller action method version In HomeController.Cs

For this, we should change the action method name in RouteConfig.cs for better loading of the page. For the first time, we will make it a start page.

Add the highlighted code in your file of RouteConfig.Cs. 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Routing; 
namespace Mvc_Version { 
    public class RouteConfig { 
        public static void RegisterRoutes(RouteCollection routes) { 
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
            routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { 
                controller = "Home", action = "Version", id = UrlParameter.Optional 
            }); 
        } 
    } 
}  

Output

The expected output is shown below.

http://localhost:49952/Home/Version

Home - Controller name
Version - Controller action method



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