European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

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

 

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Easiest Way to Make CheckBox

clock March 29, 2019 11:53 by author Peter

In this article I show you, how easy it is to make a CheckBox on ASP.NET. The use of radio buttons and checkboxes using ASP.Net programming where the function of the radio button is choosing just one selection with a circle that is a point in the middle if we choose it. While the checkbox is square shaped that there is a tick if selected. To create a function of the radio button. We will explain below:

  • First you must create a project by choosing ASP.Net which is in the File> New Project> Other Languages> Visual C #> Web> Select Empty ASP.Net Web Application.
  • Fill in the name and click OK aspproject05
  • Right Click On aspproject05 in the top right corner select ADD> New Item> Web Form. And give CheckBox.aspx as a name.
  • Next create a CheckBox, button, label by entering this code is in the <div>

<asp:CheckBox ID="chkNews" Text="Do you want to get more update ?" runat="server" />
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" /> <hr/>
<asp:Label ID="lblResult" runat="server" />


Code Description:

<Asp: CheckBox ID = "chkNews" Text = "Do you want to get more update ?" runat = "server" />
This script serves as the manufacture CheckBox with ID named chkNews, which says Do you want to get more update? sent or received by the server.

<br />
This script is used to create a new line

<Asp: Button ID = "btnSubmit" Text = "Submit" runat = "server" OnClick = "btnSubmit_Click" />
This script is used to manufacture the ID button button named btnSubmit, that says Submit sent to the server to have an action Click if the button is clicked.

<Asp: Label ID = "lblResult" runat = "server" />

This script serves to create a label with name ID lblResult the printed blanks to be sent to the server.


When you're done simply double-Click button and type in the code below:

lblResult.Text = chkNews.Checked.ToString ();


Code Description:

LblResult.Text = chkNews.Checked.ToString ();

The above code serves as outputan of chkBerita when checked or not displayed by a label that berID lblResult that are boolean. This means that when we press the button without us tick checkbox section will appear on labels False lblResult whereas if we check the CheckBox and pressing the button it will show True.

HostForLIFE.eu ASP.NET MVC Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



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

clock March 12, 2019 09:39 by author Peter

If you have worked on ASP.NET MVC, you must be familiar with how when you type in an URL, the appropriate controller is chosen, and the action fired. Today we will dig a little deeper within the MVC request life cycle. Before we start discussing its life cycle, let's briefly understand the concept of HttpHandlers and HttpModules.

Handlers are responsible for generating the actual response in MVC. They implement the IHttpHandler class and only one handler will execute per request. On the other hand, HttpModules are created in response to life cycle events. Modules can, for example, be used for populating HttpContext objects. A request can use many modules. These classes derive from IHttpModule. We are now ready to learn about the MVC Request Life Cycle. The MVC life cycle can be briefly demonstrated as below,


When a request is fired for the first time, the Application_Start method in the Global.asax file is called. This method calls the RegisterRoutes method as below,
    public class MvcApplication : System.Web.HttpApplication 
        { 
            protected void Application_Start() 
            { 
                AreaRegistration.RegisterAllAreas(); 
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
                RouteConfig.RegisterRoutes(RouteTable.Routes); 
                BundleConfig.RegisterBundles(BundleTable.Bundles); 
            } 
        } 



RegisterRoutes method stores the routes defined in that method, in a static collection in the Routetable class.
Each route has an HttpHandler defined for it. In our case above, the MapRoute method defines the HttpHandler.
Next, the URLRoutingModule is called. It matches the request route with the routes defined in the route table. It calls the GetHttpHandler method which returns an instance of an MVCHandler.

The MVCHandler calls the ProcessRequest method. The controller execution and initialization happens inside this method. ProcessRequest calls ProcessRequestInit, which uses ControllerFactory to select an appropriate controller based on the supplied route. The ControllerFactory calls the Controller Activator which uses the dependency resolver to create an instance of the controller class.

Once the controller is created its Execute method is called.

Now comes the point where the action must be executed. The execute method in the controller calls the ExecuteCore method which calls the InvokeAction method of ActionInvoker. Action Invoker determines which action must be selected based on certain conditions, depending upon the methods available, their names and the action selectors used for them.

Once the action is selected, Authentication & Authorization filters are fired next.
Once the action passes through the authentication and authorization filter checks, the model binding takes place. The information needed for the action to execute is gathered in this step.

OnActionExecuting action filters are fired next. Once the OnActionExecuting filters are executed a response for the action is generated. The thing to note here is that the response is generated at this stage, but not executed.

Next, the OnActionExecuted filters are executed.  Once all the filters have finished executing, the response is finally executed in the ExecuteResult method which is called from the InvokeActionResult by the ActionInvoker. If the response is a view or a partial view, the ViewEngine will render it, else it will be handled appropriately. The ExecuteResult will find the appropriate view using FindView or FindPartialView method. This method will search for the view in specific locations and then render it. This is the final step in generating the response.

If you would like to further dig into the MVC request life cycle, I would highly recommend Alex Wolf’s pluralsight course by the same 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 :: Server Sent Events In ASP.NET MVC

clock February 15, 2019 08:14 by author Peter

In some Web Applications, we need to show real time data to the end users, which means if any changes occur (new data available) in the Server, it needs to show an end user. For instance, you are doing chat in Facebook in one tab of your Browser. You opened another tab in the same Browser and send a message to the same user (with whom, you are doing chat in the previous chat). You will see that message will appear in both the tabs and it is called real-time push.

In order to accomplish the functionality, mentioned above, the client sends interval basis AJAX requests to the Server to check, if the data is available or not. ServerSentEvents(SSE) API helps ensure the Server will push the data to the client when the data is available in the Server.

What are Server Sent Events?
SSE is an acronym and stands for Server Sent Events. It is available in HTML5 EventSource JavaScript API. It allows a Web page to get the updates from a Server when any changes occurs in the Server. It is mostly supported by the latest Browsers except Internet Explorer(IE).

Using code
We are going to implement a requirement like there is a link button and click on it and it displays current time each second on an interval basis.
In order to achieve the same, we need to add the following action in HomeController. It sets response content type as text/event-stream. Next, it loops over the date and flushes the data to the Browser.
    public void Message() 
    { 
        Response.ContentType = "text/event-stream"; 
     
        DateTime startDate = DateTime.Now; 
        while (startDate.AddMinutes(1) > DateTime.Now) 
        { 
            Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString())); 
            Response.Flush(); 
     
            System.Threading.Thread.Sleep(1000); 
        } 
         
        Response.Close(); 
    }


Once we are done with the Server side implementation, it's time to add the code in the client side to receive the data from the Server and displays it.

First, it adds a href link, which calls initialize() method to implement SSE. Second, it declares a div, where the data will display. Thirdly, it implements Server Sent Events(SSE) through JavaScript with the steps, mentioned below.
    In the first step, it checks whether SSE is available in the Browser or not. If it is null, then it alerts to the end user to use other Browser.
    In the second step, if SSE is available, then it creates EventSource object with passing the URL as a parameter. Subsequently, it injects the events, mentioned below.

        onopen- It calls when the connection is opened to the Server
        onmessage- It calls when the Browser gets any message from the Server
        onclose- It calls when the Server closes the connection.

    <a href="javascript:initialize();" >Click Me To See Magic</a> 
    <div id="targetDiv"></div> 
     
    <script> 
         
        function initialize() { 
            alert("called"); 
     
            if (window.EventSource == undefined) { 
                // If not supported 
                document.getElementById('targetDiv').innerHTML = "Your browser doesn't support Server Sent Events."; 
                return; 
            } else { 
                var source = new EventSource('../Home/Message'); 
     
                source.onopen = function (event) { 
                    document.getElementById('targetDiv').innerHTML += 'Connection Opened.<br>'; 
                }; 
     
                source.onerror = function (event) { 
                    if (event.eventPhase == EventSource.CLOSED) { 
                        document.getElementById('targetDiv').innerHTML += 'Connection Closed.<br>'; 
                    } 
                }; 
     
                source.onmessage = function (event) { 
                    document.getElementById('targetDiv').innerHTML += event.data + '<br>'; 
                }; 
            } 
        } 
    </script>


Output

Here, we discussed about SSE(Server Sent Events). It is very important API available in HTML5. It helps to push data from the Server to the client when any changes occurs in the Server side. If you want to use a bidirectional communication channel, you can use HTML5 Web Sockets API. The disadvantage of SSE is it is Browser dependent. If the Browser doesn't support SSE, then the user can't see the data, but it is easy to use it. You can also use SignalR for realtime pushing the data to the end user.

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 :: Stepwise Display Multiple Partial View Using JSON in MVC 5

clock November 9, 2018 10:58 by author Peter

Here are the steps:
Step 1: Create the basic structure of your project, View, multiple partial views View Model,

Step 2: Create your base Controller as in the following,
    public class BaseController: Controller 
    { 
        protected internal virtual CustomJsonResult CustomJson(object json = null, bool allowGet = true) 
        { 
            return new CustomJsonResult(json) 
            { 
                JsonRequestBehavior = allowGet ? JsonRequestBehavior.AllowGet : JsonRequestBehavior.DenyGet 
            }; 
        } 
    } 


It is just small modifications if JSON is not provided handle it. And use this Controller as base controller.

Step 3: Add Class Controller helper which helps you to convert partial view into the string format as in the following,
    public static class ControllerHelper 
    { 
        public static string RenderPartialViewToString(ControllerContext context, string viewName, object model) 
        { 
            var controller = context.Controller; 
            var partialView = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName); 
            var stringBuilder = new StringBuilder(); 
            using(var stringWriter = new StringWriter(stringBuilder)) 
            { 
                using(var htmlWriter = new HtmlTextWriter(stringWriter)) 
                { 
                    controller.ViewData.Model = model; 
                    partialView.View.Render(new ViewContext(controller.ControllerContext, partialView.View, controller.ViewData, new TempDataDictionary(), htmlWriter), htmlWriter); 
                } 
            } 
            return stringBuilder.ToString(); 
        } 
    } 

Step 4: Your action code is below. I have added the 2 partial views. Basically we are converting the partial view with objects into the string format.
    public JsonResult CreatePartialView() 
    { 
        MyMultipleUpdateViewModel obj = new MyMultipleUpdateViewModel(); 
        obj.myTest1ViewModel = new MyTest1ViewModel(); 
        obj.myTest1ViewModel.MyTestUpdate = "Test1" + DateTime.Now.ToString(); 
        obj.myTest2ViewModel = new MyTest2ViewModel(); 
        obj.myTest2ViewModel.MyTestUpdate = "Test2" + DateTime.Now.ToString(); 
        var json = new 
        { 
            Header = "Header", Footer = "Footer" 
        }; 
        return CustomJson(json).AddPartialView("_MyTest1PartialView", obj).AddPartialView("_MyTest2PartialView", obj); 
    } 

Step 5: In View display this JSON data ajax in below way . In below code PartialViewDiv1 and PartialViewDiv2 are two divs in which two partial views will be displayed. I have two partial views you may load more partial views.
    <h2>Index</h2> 
    <script type="text/javascript" src="@Url.Content(" ~/Scripts/jquery-1.10.2.js ")"></script> 
    <script type="text/javascript" src="@Url.Content(" ~/Scripts/jquery.unobtrusive-ajax.min.js ")"></script> 
    <script> 
    function GetData(url, onSuccess) 
    { 
        $.ajax( 
        { 
            type: "GET", 
            cache: false, 
            url: url, 
            dataType: "json", 
            success: function(data, textStatus, jqxhr) 
            { 
                onSuccess(data.Json, data.Html); 
            }, 
            error: function(data, text, error) 
            { 
                alert("Error: " + error); 
            } 
        }); 
        return false; 
    } 
     
    function UpdateDiv(json, html) 
    { 
        $("#PartialViewDiv1").html(html[0]); 
        $("#PartialViewDiv2").html(html[1]); 
    } 
    </script> 
    <input type="button" onclick="GetData('/DisplayMutiplePartialView/CreatePartialView', UpdateDiv);" value="Display Multiple Partial View" /> 
    <br> 
       <br> 
          <div id="PartialViewDiv1"></div> 
       <br> 
       <br> 
          <div id="PartialViewDiv2"></div> 
       <br> 
    <br> 


Step 6: Run application and use URL,
It will appear as below

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.

 



European ASP.NET MVC 6 Hosting :: ASP.NET MVC 6 Web API Routes and ApiController

clock October 5, 2018 09:47 by author Peter

ASP.NET MVC 6 Web API Project

ASP.NET MVC 6 introduces several new project types after you initially pick that you want to develop an ASP.NET MVC 6 Web Application. One of those application types is the new Web API Project.


If you choose the Web API Project, a new Web API Controller Class is created for you to provide an example of responding to Get, Post, Put, and Delete requests for your API.


public class ValuesController : ApiController {

   // GET /api/values
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }

    // GET /api/values/5
    public string Get(int id) {
        return "value";
    }

    // POST /api/values
    public void Post(string value) {}


    // PUT /api/values/5
    public void Put(int id, string value) {}

    // DELETE /api/values/5
    public void Delete(int id) {}
}


With the Web API Project you will also notice a new API specific route added to the RouteTable in Global.asax.cs.

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);


Running the project and navigating to ~/api/values will display a list of the values in XML Format. I removed the XML namespacing to keep things simple.

<ArrayOfString>
    <string>value1</string>
    <string>value2</string>
</ArrayOfString>

If you change the Accept Header so that you will only accept JSON, the same controller action will send the values via JSON instead.

["value1","value2"]

Web API Controller Class - ApiController in ASP.NET MVC 4

Creating a new Web API Controller Class is as simple as using the Add Controller Recipe in ASP.NET MVC 4 and choosing the Empty API controller Tempate.



Or, you could just create one via Add Item which has a new Web API Controller Class as an option.


I created a simple ProductsController that handles all the CRUD options for products in a mythical e-commerce website.


public class ProductsController : ApiController {
    private readonly IRepository<Product> _repository;

    public ProductsController(IRepository<Product> repository) {
        _repository = repository;
    }

    public IEnumerable<Product> Get() {
        return _repository.Queryable();
    }

    public Product Get(int id) {
        var product = _repository.Get(id);

        if (product == null)
            throw new HttpResponseException(HttpStatusCode.NotFound);

        return product;
    }

    public HttpResponseMessage<Product> Post(Product product) {
        _repository.Add(product);

        var response = new HttpResponseMessage<Product>
            (product, HttpStatusCode.Created);
        response.Headers.Location = new Uri(Request.RequestUri,
            Url.Route(null, new {id = product.Id}));

        return response;
    }

    public Product Put(int id, Product product) {
        var existingProduct = _repository.Get(id);

        if (existingProduct == null)
            throw new HttpResponseException(HttpStatusCode.NotFound);

        _repository.Save(product);

        return product;
    }

    public HttpResponseMessage Delete(int id) {
        _repository.Delete(id);

        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }
}

You can see that in some instances I am just returning a Product and in other instances I am returning a more informational HttpResponseMessage. For example, in the case of the Post of a new Product, I need to tell the REST Client the new location of the newly added product in the header. In other actions I am also throwing a HttpResponseException if the resource requested is not found. Validation, Logging, and other concerns are being done in various ActionFilters just like in your normal ASP.NET MVC Projects. Try to pull those cross-cutting concerns out of the main logic as much as possible.


ASP.NET Web API OData Syntax for Paging and Querying

If you want to enable various paging and querying of products you can make a slight change to the Get ApiController Action and return an IQueryable<Product> as opposed to IEnumerable<Product>.

public IQueryable<Product> Get() {
    return _repository.Queryable();
}

Now from your browser you can add paging, filtering, sorting, and other options to shape the data. Here is an example call that does paging and sorting.

api/products?$skip=2&$top=2&$orderby=Title

The XML Response by the browser is:

<ArrayOfProduct>
    <Product>
        <Id>3</Id>
        <Title>RipStik</Title>
        <Price>69.00</Price>
    </Product>
    <Product>
        <Id>4</Id>
        <Title>Shred Sled</Title>
        <Price>49.00</Price>
    </Product>
</ArrayOfProduct>


Or the JSON Response:

[{"Id":3,"Price":69.00,"Title":"RipStik"},
{"Id":4,"Price":49.00,"Title":"Shred Sled"}]


Conclusion

ASP.NET Web API integration with ASP.NET MVC 4 is really slick. Now you can easily create an API for your website using the new ApiController Base Class to respond to REST Clients.

 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: Is MVC Replacing ASP.NET Web Forms?

clock September 18, 2018 09:53 by author Peter

We often think that one technology will be totally replaced by a new release or new version of technology. This article tries to dicuss that and similar issues and I will share my industry experience, not just what I have seen in India (the largest IT Solutions Provider to the world) but also in the USA.

I consider this to be a very hot topic and a good candidate of debate but I will try to share my thoughts on such a burning topic. This article does not highlight or defame any technology, I am just going to provide my perspective as I have seen, experienced and advised to various clients and software teams.

Why new Versions

The principle “Change is Constant” applies very well to the software industry and I respect this overflow of information. Because this gives me reason to “Keep Learning and stay ahead of the Curve”. By saying so I didn't mean that someone must learn anything and everything you can get your hands on. No, certainly not, but before I explain this any further let's take a step back and understand “Why new Versions” keep coming.

We are fortunate that we have seen complete transition of the software industry from Desktop to Web to Mobile, future generations may not witness this great and life changing shift. Also, I recall my days when I was working and studying software in 1995, no one imagined that there will be MVC, WPF, WCF, so many versions of .NET and SQL Server and so on. Industry was happy with Microsoft Access, FoxPro, C, C++ and Oracle and so on. But our needs keep changing, they evolved and then shell is broken to have huge expansion and today we have many kinds of software technology and server products from client-side to server-side to mobile and hand-held and many more. We moved from on premise to the Cloud and Machine Learning is helping to dictate patterns and suggest needs.

This is why software companies keep building the latest and newest technologies to enable and empower the world to build for the future. When they release a version of a technology or language and they discover some issues or new features in that then they release newer versions and this in a chain-reaction process and it will not stop.

Oh, then I will die Learning

As per Darwin's Evolution Theory “Survival of the Fittest”, "fit" refers to "best adapted to the current environment". Here you simply replace environment with the software industry. I am one of you and I am not saying that everyone must learn everything but what I suggest is to stick to your technology of choice and have good knowledge of the offered tools and technologies and various versions and when to use which one.

Also, you don't necessarily need to understand every single thing. For example, I only focus on .NET and related technologies, if anything falls beyond this area then I am not bothered. To be more precise, I don't understand Microsoft CRM, SharePoint, System Center, SQL Server Database Administration and few more things like that.

But this is not my weak point because “I continue to build my .NET Muscle” and continue to learn about what helps me build Enterprise solutions using Microsoft .NET.

So choose your area of interest and where you have invested and then keep learning in a similar field and then you will no longer find it challenging because if you observe, new versions come after every few years and that must be otherwise it will be no fun!

Hmm, so Isn't MVC Replacing ASP.NET Web Forms

Such decisions are not final and have no concrete answers. Yes, the industry changes their needs and so new technologies such as MVC and WPF takes over. This definitely doesn't mean that ASP.NET Web Forms is replaced or it's dead. If you understand the Microsoft Web fundamentals, MVC is based on ASP.NET and industry is trying to shift as and when they can from Web Forms to MVC and reap the benefits it offers.

Did you know that MVC is much older than ASP.NET? Yes, ASP.NET 1.0 was released in 2002 and MVC was created in 1979 originally named as “Thing-Model-View-Controller” but later simplified to be known as MVC.

In my view I consider that there are now two technologies to build Web Solutions using Microsoft and based on your needs you can pick one that works well for you. Usually such technology selections are made by architects assigned to the project.

So there is no such Golden Rule that every new or existing application must be either created using MVC or migrated to MVC because MVC is the latest and future the of web. Though it is.

Architectural Thinking: Brownfield Vs Greenfield Applications

All software applications you have worked or will work in future are either Brownfield or Greenfield.

  • Brownfield Development: When any existing or legacy applications need to have new features or changes to address business needs, it is known as brownfield. In such situations, unless you are building a new module or component, you have less, limited or no scope to use new architectural styles, patterns and so on. The very reason of such limitations is because those old applications are built using an old version of technologies and the latest versions of one technology/framework and many are not be compatible with old versions.
  • Greenfield Development: When a brand-new project is being envisioned and no previous work is done in that or a related area then it's called Greenfield. In the software industry it doesn't happen very often. But whenever it happens its the architect's responsibility to determine what the best technology is to address business needs.

Hence, it's not appropriate to say that because MVC is so new hence every new web application must be made using MVC or if WPF is available in addition to Windows Forms so every desktop application must be made using WPF. Whatever is the case neither ASP.NET Web Forms nor Windows Forms can be totally ignored.

Why and Why not the Latest Technologies should be chosen

First the reasons why not.

  1. It's Brownfield and new technology doesn't fit anywhere.
  2. If new technology or versions are introduced then it will cause many build errors due to outdated references of non-supported library references.
  3. Business goals and software quality are not compromised by continuing to use current and available technologies like ASP.NET Web Forms over MVC or Windows Forms over WPF.
  4. You are not investing money in any extra off-the-shelf tools to handle issues that could have been handled by the latest versions of similar area of technologies, for example MVC instead of ASP.NET Web Forms, or WPF over Windows Forms.
  5. Teams often might not have a certain skill set that allows them to proceed with development using new technology options
  6. Budget allocation from a client often may impact your decision to use and develop using the latest technologies.
  7. If the core/bestselling features of a new candidate technology (MVC or WPF) are not being used at least up to 50% then you have done nothing.
  8. Considering how soon the client and business wants to have an application ready, it turns being a major factor to dictate the technology of choice.
  9. The client and business doesn't care how you do it; what matters is the end-result and a workable / good-enough software.
  10. No way to use old legacy downstream applications with the latest available technologies.

Why develop using Latest Technologies

  1. Greenfield software solution and no legacy or old piece of code is being used.
  2. Focus is more on Robustness, Testability, Object Oriented design and quality. (This doesn't mean previous technology can't accomplish these; it's about ease and in-built features and offerings).
  3. Amazing team with great skills to learn new technologies and adapt the changes.
  4. Company's vision is to showcase products build using latest technologies.
  5. Client themselves want the solution to be developed using latest technologies and have budget to support that.

Why MVC over ASP.NET Web Forms then

Note: this section assumes that you are aware of MVC benefits and the general technical terms used below.

  1. Separation of Concerns is the core of MVC.
  2. Single Responsibility Principle is done by default.
  3. Unified and even better framework to work on WebAPI, Mobile, HTML 5, CSS3, Security and Deployment (including Azure).
  4. Unit testing is easily done to have stable, robust and quality software solutions delivered continuously.
  5. Fast screen generation for CRUD operations via Scaffolding.
  6. Convention over configuration.

Summary
Based on my experience as an architect in the industry I would like to summarize that it's very hard for any organization to keep up with the latest version and technologies all the time because by the time you become comfortable with one version the newer is around the corner. So if you are working on MVC 4, then see if you can learn and try some application being developed on your own. Or if you just happen to be in the ASP.NET Web Forms world until now then I would encourage you to try converting that application to MVC for your personal benefit. This will force you to learn new technology and apply that learning. If you have made some progress in that then in the next interview you can proudly showcase your MVC knowledge and say that you have migrated ASP.NET Web Forms to MVC.



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>



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in