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 5 Hosting - HostForLIFE.eu :: What is And Why We Do State Management In ASP.NET MVC

clock October 17, 2019 11:58 by author Peter

If your website consists of multiple pages and you want to share the data appearing on the 2nd page to the 4th page, then you will have to use State Management feature of ASP.NET. Since our whole communication through the internet is done using HTTP Protocol and when a client(Browser) sends request to the server then it establishes a connection using HTTP and server gives the response, after that, connection will be disconnected. Actually each time a connection is created for a request and after the response it will be disconnected, which means if you have some data on first page and want to get it on the 10th, then it will be impossible to do it without state management feature. If you don’t use this feature then you will have to go the database for each single request(if you require data) which creates huge network traffic with increasing number of users.

You can manage the state by the following ways,

    Client Side State Management

        Cookie
        QueryString
        Hidden Form Field

    Server Side State Management

        Session
        TempData

Note
Client Side Management means nothing will be stored on server side but on client side and reverse will happen on server side. (i.e. all data will be on server side)
 
Client Side State Management
 
Cookie
 
Cookie is a text file with some information in it, generated by the most websites that you visit and then saved it in your browser(folder or subfolder) if you have enabled the cookie option.
 
Advantages

    All information is stored on client side.
    With cookie you can use the remember me option, some websites that you visit first time which then asks you or you can choose a language of your choice and then the information on website appears in that particular language every time you visit(depends upon expiry date). Also, you have seen some time, that this kind of option will work on your machine(laptop) not on your other devices, so behind the scenario there is a cookie.

Disadvantages

    You can disable cookies in your browser settings. This is a major drawback and if you have use cookies in your site for some features then it will cost you badly.
    Less secure since you can view the data in cookies by opening DevTools(in chrome)

Cookie types

    Persistent (Can specify expiry time)
    Non Persistent(Use for sessions and will expire as the browser or tab is closed in which the web app is opened)

The recommended Data limit: 4096bytes(4kb). Size should not exceed this value as you send data (>4KB) using cookie on every request, then more broadband is used because in some scenarios uploading speed can be lesser.
 
QueryString
 
With QueryString, you can specify the data in the URL tab.

    Starts with a question mark(?)
    If there are two values that you are sending, then it will be separated with &.

    There is no limit on length of queryString but the most recommended length for query string is 1024 characters. Try your queryString to be in that range because some web servers will through 413 error(Entity too long to respond)

Advantages

    Can’t be disabled by client
    Can be used to share information between pages and most suitable where the information is static(remains static for whole website)

    e.g.You request to go the specific page but the login is required and you fill the form successfully and then redirected to page where you were before login.

Disadvantages

    You require information on 4th page which is present on 1st page, then you will have to fetch the info again from the database and then send it(if the data is dynamic or changed in recent activity)
    The information that we send using QueryString gets visible to all users so it can’t be used to send sensitive data but if require then encrypt it then send.(an extra effort)

Hidden Field

    Share information between multiple requests on same page.
    If there is Single page application(SAP) or there is a page like login page where you given three attempts to user for entering right username and password then you can use it as a counter.

 
Advantages
 
Can’t be disabled by client.
 
Disadvantages
 
Need Encryption because the value can be seen by using DevTools of browser.



ASP.NET MVC Hosting - HostForLIFE.eu :: Preventing Cross Site Request Forgery In MVC

clock September 26, 2019 11:14 by author Peter

What is Cross-Site Request Forgery
Cross-Site Request Forgery (CSRF) is a process in which a user first signs on to a genuine website (e.g. facebook.com) and after successful login, the user opens another website (malicious website) in the same browser.
 
Both websites are opened in the same browser. Malicious website will display some links to the user and asks the user to click on those links. User clicks on the links displayed on a malicious website, the malicious website sends a request using the existing session of genuine website. Web server of genuine website treats this request as a valid request and assumes that it is coming from a valid user so it executes the request and provides a proper response. A malicious website can perform harmful operations on genuine website.
 
In order to solve this problem, we expect the Action Method of genuine website to recognize the source of the request, whether the request is coming from genuine website or from a malicious website. This can be achieved by using the [ValidateAntiForgeryToken] attribute in ASP.Net MVC.
 
How to Implement CSRF Security in MVC
In order to implement CSRF security in MVC, first, we need to use HTML helper @Html.AntiForgeryToken() in view. It should be placed inside the BeginForm() method in view.
 
Next, we need to add [ValidateAntiForgeryToken] attribute on the action method which will accept HTTP post request. We need to do only these 2 changes and now MVC will prevent CSRF attacks.
 
How ValidateAntiForgeryToken works
How ValidateAntiForgeryToken prevents CSRF attacks?


First, the user will open genuine website in the browser. User login to genuine website. After login, genuine website sends Authentication cookie and Verification token. Verification token has randomly generated alphanumeric values. The verification token is stored in the cookie as well as in hidden field on client-side. When HTML form is submitted to the server, the verification token is submitted as a cookie as well as a hidden field. On the server-side, both are checked if they are same or not? If both are same then request is valid. If they are different or one of them is missing then request is treated as invalid request and will be rejected automatically by MVC.
 
When a user opens a malicious website in a new tab of the same browser, the malicious website will display some links and ask the user to click on those links. This website already has a script to send the request to genuine website. When the user clicks on links, the malicious website sends a request to genuine website. Since request is being sent to genuine website, the browser automatically submits Authentication cookie to Action method of genuine website but here, the hidden field is missing. The Action method has [ValidateAntiForgeryToken] attribute so it checks whether Authentication cookie and hidden field has same value but here, the hidden field is missing so the request is treated as invalid and it is rejected by MVC.
 
Practical Implementation
Wherever you have a Form, use @Html.AntiForgeryToken() inside the form and action method for accepting the HTTP Post should have ValidateAntiForgeryToken attribute. These are the only change, the rest of the process will be taken care of by ASP.Net MVC.
 
Please see the below HTML view where I have added@Html.AntiForgeryToken()
    @using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
       @Html.AntiForgeryToken() 
       <div class="form-row"> 
       <div class="form-group col-md-6"> 
          @Html.LabelFor(temp => temp.ProductName) 
          @Html.TextBoxFor(temp => temp.ProductName, new { placeholder = "Product Name", @class = "form-control" }) 
          @Html.ValidationMessageFor(temp => temp.ProductName) 
       </div> 
    <div class="form-group col-md-6"> 
       @Html.LabelFor(temp=>temp.Price) 
       @Html.TextBoxFor(temp=>temp.Price,new { @class="form-control",placeholder="Price"}) 
    </div> 
    </div> 
    @Html.ValidationSummary() 
       <button type="submit" class="btn btn-success">Create</button> 
       <a class="btn btn-danger" href="/products/index">Cancel</a> 
    } 

Below is the action method where I have added [ValidateAntiForgeryToken] attribute.
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create(Product p) 
       { 
       ProductDBContext db = new ProductDBContext(); 
       if (ModelState.IsValid) 
       { 
          db.Products.Add(p); 
          db.SaveChanges(); 
          return RedirectToAction("Index"); 
       } 
       else 
       { 
          return View(); 
    } 
    } 

Summary
In this blog, I have explained Cross-Site Request Forgery(CSRF), its steps and what changes we need to do in MVC application to prevent CSRF attacks.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Bootstrap Tab Strip in ASP.NET MVC

clock September 18, 2019 12:47 by author Peter

In this post, we will see how to render given below bootstrap Tab script in Asp.net MVC 5 view.

Here the number of tabs displayed in view would depend on count of members in the list.

1. Create ASP.NET MVC 5 project.
 
2. Define Member class as follows in “Member.cs” file
    public class Member 
    { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    } 

3. Add view to create action method and pass a list of members from controller Action method to razor view file. i.e. “create.cshtml”
    public ActionResult Create() 
    { 
    List<Member> members = new List<Member>(); 
    members = GetMemberList(); 
    return View(members); 
    } 
    private List<Member> GetMemberList() 
    { 
    List<Member> members = new List<Member>(); 
    members.Add(new Member{ Name = "member1" }); 
    members.Add(new Member { Name = "member2" }); 
    members.Add(new Member { Name = "member3" }); 
    members.Add(new Member { Name = "member4" }); 
    members.Add(new Member { Name = "member5" }); 
    return members; 
    } 


4. Using CSS classes, we can create a tabscript in our “create.cshtml” as shown below:
    @model IEnumerable<Member> 
    <div class="container"> 
    @if (Model.ToList().Count > 0) 
    { 
    <ul class="nav nav-tabs" role="tablist"> 
    @{int i = 0; 
    foreach (var item in Model) 
    { 
    if (i == 0) 
    { 
    <li class="nav-item"> 
    <a class="nav-link active" data-toggle="tab" href="#@item.Name">@item.Name</a> 
    </li> 
    } 
    else 
    { 
    <li class="nav-item"> 
    <a class="nav-link" data-toggle="tab" href="#@item.Name">@item.Name</a> 
    </li> 
    } 
    i++; 
    } 
    } 
    </ul> 
    <div class="tab-content"> 
    @foreach (var item in Model) 
    { 
    <div id="@item.Name" class="container tab-pane active"> 
    <br> 
    <h3>@item.Name 's Tab Area </h3> 
    </div> 
    } 
    </div> 
    } 
    </div> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> 



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How To Use jQuery To Consolidate AutoComplete Function

clock September 13, 2019 11:51 by author Peter

jQuery UI has an AutoComplete widget. The AutoComplete widget is quite nice and straight forward to use. In this post, I will show you how to use jQuery AutoComplete widget to consolidate AutoComplete function in ASP.NET MVC application.

Step 1

The first step is to add the jQuery scripts and styles. With ASP.NET MVC, the following code does the work:

@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")   
@Scripts.Render("~/bundles/jqueryui")

Step 2

Using the AutoComplete widget is also simple. You will have to add a textbox and attach the AutoComplete widget to the textbox. The only parameter that is required for the widget to function is source. For this example, we will get the data for the AutoComplete functionality from a MVC action method.

$(document).ready(function () {
    $('#tags').autocomplete(
        {
            source: '@Url.Action("TagSearch", "Home")'
    });
})

In the above code, the textbox with id=tags is attached with the AutoComplete widget. The source points to the URL of TagSearch action in the HomeController: /Home/TagSearch. The HTML of the textbox is below:

<input type="text" id="tags" />


Step 3

When the user types some text in the textbox, the action method (TagSearch) is called with a parameter in the request body. The parameter name is term. So, your action method should have the following signature:

public ActionResult TagSearch(string term)
{
    // Get Tags from database
    string[] tags = { "ASP.NET", "WebForms",
                    "MVC", "jQuery", "ActionResult",
                    "MangoDB", "Java", "Windows" };
    return this.Json(tags.Where(t => t.StartsWith(term)),
                    JsonRequestBehavior.AllowGet);
}

Now, the AutoComplete functionality is complete!

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 Hosting UK - HostForLIFE.eu :: Session Handling for Synchronous/Asynchronous Requests in ASP.NET MVC Hosting with jQuery

clock September 6, 2019 12:18 by author Peter

Basic use of session in ASP.NET MVC is as follows:

  • Check user is logged in or not
  • to carry authorization data of user logged in
  • to carry temporary alternative data
  • Check session Timeout on user action for every controller

Using asynchronous (AJAX) request it's a very common state of affairs to use jquery AJAX or unobtrusive AJAX API of ASP.NET MVC 5 to create asynchronous request in MVC 5. Each jquery AJAX and unobtrusive AJAX square measure very powerful to handle asynchronous mechanism. however in most things, we like better to use jquery AJAX to possess fine tuned control over the application. And currently suppose we wish to see the session timeout for every asynchronous call in our application. we are using JSON to grab an information on form and send it with asynchronous request. Therefore we dropped in situation where:

1. Normal direct won’t work well
RedirectToAction("LoginView", "LoginController");

2. We need to ascertain session timeout in action technique. A repetitive code in every action method therefore reduced code reusability and maintainability.

if (session.IsNewSession || Session["LoginUser"] == null) { //redirection logic 

We can use base controller class or take advantage of action filters of ASP.NET MVC 5. using base controller class and preponderant OnActionExecuting methodology of Controller class:
public class MyBaseController : Controller

{

    protected override void OnActionExecuting(ActionExecutingContext filterContext)

   {

        HttpSessionStateBase session = filterContext.HttpContext.Session;
        if (session.IsNewSession || Session["LoginUser"] == null)

        {

            filterContext.Result = Json("Session Timeout", "text/html");

        }

   }

}

And inheriting Base Class:

public class MyController : BaseController

{

//your action methods…

}

Limitation of this approach is that it covers up every action method.Using action filter attribute class of ASP.NET MVC 5. Therefore we will fine tune every controller action as needed.
      [AttributeUsage(AttributeTargets.Class |

    AttributeTargets.Method, Inherited = true, AllowMultiple = true)]

     public class SessionTimeoutFilterAttribute : ActionFilterAttribute

     {
   
       public override void OnActionExecuting(ActionExecutingContext filterContext)

    {

       HttpSessionStateBase session = filterContext.HttpContext.Session;

        // If the browser session or authentication session has expired

        if (session.IsNewSession || Session["LoginUser"] == null)

        {

            if (filterContext.HttpContext.Request.IsAjaxRequest())

            {

                
JsonResult result = Json("SessionTimeout", "text/html");
                filterContext.Result = result;

            }

            else

            {

                // For round-trip requests,

               filterContext.Result = new RedirectToRouteResult(

                new RouteValueDictionary {

                { "Controller", "Accounts" },

                { "Action", "Login" }

                });

            }

        }

        base.OnActionExecuting(filterContext);

    }

}


Jquery code at client side

$.ajax({

    type: "POST",

    url: "controller/action",

    contentType: "application/json; charset=utf-8",

    dataType: "json",

    data: JSON.stringify(data),

    async: true,

    complete: function (xhr, status) {

            if (xhr.responseJSON == CONST_SESSIONTIMEOUT) {

                RedirectToLogin(true);

                return false;

            }

            if (status == 'error' || !xhr.responseText) {

                alert(xhr.statusText);

            }

       }

    });




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 Hosting - HostForLIFE.eu :: Install MVC 4 in Visual Studio 2010

clock June 28, 2019 09:43 by author Peter

We can develop MVC applications in Visual Studio 2010. Visual Studio 2010 includes MVC 2 by default. We can also install both MVC 3 and MVC 4 in Visual Studio 2010. In this article, I go through step-by-step how to install MVC 4 in Visual Studio 2010.

ASP.NET MVC 4 includes all features of MVC 3 and also includes the following:

  • The ASP.NET Web API is a framework for building and consuming HTTP services that can reach a broad range of clients, including browsers, phones, and tablets. The ASP.NET Web API is great for building services that follow the REST architectural style, plus it supports RPC patterns.
  • ASP.NET Web Pages and the new Razor syntax provide a fast, approachable, and lightweight way to combine server code with HTML to create dynamic web content.
  • Web Optimization is a framework for bundling and minifying scripts and CSS files.
  • NuGet, a free, open source developer focused package management system for the .NET platform is intended to simplify the process of incorporating third-party libraries into a .NET application during development.

Step 1: Download and Install Visual Studio 2010 Service Pack 1

Visual Studio 2010 SP1 is required to use MVC 4 in Visual Studio 2010 so we need to install it on our machine then install MVC 4. We can download it from the Microsoft Download Center and go through the following link.
http://www.microsoft.com/en-in/download/details.aspx?id=23691

We download the "VS10sp1-KB983509.exe" file and click on it and follow the steps as given in the process. But it is a web platform install so we need an internet connection to install VS SP1. If we want to install VS SP1 without an internet connection then we need to download the ISO file of VS SP 1. We can download the ISO file for VS SP1 from the same link under Install Instructions. Its size is 1.48 GB (1,590,734,349 bytes).


After installation of VS 2010 SP 1 we wil proceed to install MVC 4.

Step 2: Download MVC 4
We can download MVC 4 from the Microsoft Download Center and go through the following link:
http://www.microsoft.com/en-us/download/details.aspx?id=30683


Click on the "Download" button and the download will start within 30 seconds.

Step 3: Run MVC 4
Now we have the MVC 4 set up file ("AspNetMVC4Setup.exe") to install MVC 4. Double-click on it and it runs.

Accept the License Agreement and click on "Install".

The screen above takes several minutes so don't click on cancel or close window. After a successful installation, we get a success message on the installation screen.


Step 4: Check whether the install was successful
Now we will create a new project from Visual Studio 2010.
Go to "File" -> "New" -> "Project...".

We are notified that the MVC 4 template is ready to be used in Visual Studio 2010 so MVC 4 is successfully installed and ready to use.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: HTTP Verbs In MVC 5

clock June 18, 2019 12:12 by author Peter

In this article, I will explain the concept of HTTP verbs in MVC 5. I will also explain the various types of HTTP verbs in MVC 5 and how it works in the project.

What is HTTP?

  • HTTP stands for hypertext transfer protocol.
  • This protocol works while working with a client-server application.
  • This protocol provides communication between the client and the server.

HTTP provides methods (verbs) for the actions performed on a response. HTTP verbs are used on an action method. HTTP provides the following main verbs.

  • Get
  • Post
  • Put
  • Delete

HTTP Get
This verb is used to get existing data from the database. In HttpGet, data travels in the URL only. To use the HttpGet method, we use HttpGet attribute on the Action method. It is also the default HTTP verb.

Example
domain.com/student/GetStudent/1
domain.com/student/GetStudent?studentid=1


[HttpGet] 
public object GetStudent(int studentid) 

   // code here 


HTTP Post

This verb is used while we have to create a new resource in the database. In HttpPost, data travels in the URL and body. To use HttpPost method, we use HttpPost attribute on the Action method.

Example
domain/student/Studentsave


Body - Json body
[HttpPost] 
public object Studentsave(studentclass obj) 



HTTP Put

This verb is used while we have to update an existing resource in the database. In HttpPut, the data travels in the URL and body. To use HttpPut method, we use HttpPut attribute on the Action method.

Example
domain.com/student/studentupdate/1

Body- Json body
[HttpPut] 
public object Studentupdate(int studentid ,Studentclass objVM) 



HTTP Delete
This verb is used while we have to delete the existing resources in the database. In HttpDelete, data travels in the URL and body. To use HttpDelete, we use HttpDelete attribute on the Action method.

Example

domain.com/student/studentdelete/1

[HttpDelete]   
public object Studentupdate(int studentid)   
{   
}  
HostForLIFE.eu ASP.NET MVC 6 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 Germany - HostForLIFE.eu :: How to Create RSS feeds in ASP.NET MVC?

clock April 26, 2019 11:01 by author Peter

ASP.NET MVC 6 Hosting  is the technology that brought me to Microsoft and the west-coast and it’s been fun getting to grips with it these last few weeks. Last week I needed to expose RSS feeds and checked out some examples online but was very disappointed. If you find yourself contemplating writing code to solve technical problems rather than the specific business domain you work in you owe it to your employer and fellow developers to see what exists before churning out code to solve it.

The primary excuse (and I admit to using it myself) is “X is too bloated, I only need a subset. I can write that quicker than learn their solution.” but a quick reality check:

1. Time – code always takes longer than you think

2. Bloat – indicates the problem is more complex than you realize

3. Growth – todays requirements will grow tomorrow

4. Maintenance – fixing code outside your business domain

5. Isolation – nobody coming in will know your home-grown solution

The RSS examples I found had their own ‘feed’ and ‘items’ classes and implemented flaky XML rendering by themselves or as MVC view pages.

If these people had spent a little time doing some research they would have discovered .NET’s built in SyndicatedFeed and SyndicatedItem class for content and two classes (Rss20FeedFormatter and Atom10FeedFormatter )  to handle XML generation with correct encoding, formatting and optional fields. All that is actually required is a small class to wire up these built-in classes to MVC.

using System;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace MyApplication.Something
{
    public class FeedResult : ActionResult
    {
        public Encoding ContentEncoding { get; set; }
        public string ContentType { get; set; }
        private readonly SyndicationFeedFormatter feed;
        public SyndicationFeedFormatter Feed{
            get { return feed; }
        }
        public FeedResult(SyndicationFeedFormatter feed) {
            this.feed = feed;
        }
        public override void ExecuteResult(ControllerContext context) {
            if (context == null)
                throw new ArgumentNullException("context");
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/rss+xml";
            if (ContentEncoding != null)
                response.ContentEncoding = ContentEncoding;
            if (feed != null)
                using (var xmlWriter = new XmlTextWriter(response.Output)) {
                    xmlWriter.Formatting = Formatting.Indented;
                    feed.WriteTo(xmlWriter);
                }
        }
    }
}

In a controller that supplies RSS feed simply project your data onto SyndicationItems and create a SyndicationFeed then return a FeedResult with the FeedFormatter of your choice.

public ActionResult NewPosts() {
    var blog = data.Blogs.SingleOrDefault();
    var postItems = data.Posts.Where(p => p.Blog = blog).OrderBy(p => p.PublishedDate).Take(25)
        .Select(p => new SyndicationItem(p.Title, p.Content, new Uri(p.Url)));
    var feed = new SyndicationFeed(blog.Title, blog.Description, new Uri(blog.Url) , postItems) {
        Copyright = blog.Copyright,
        Language = "en-US"
    };
    return new FeedResult(new Rss20FeedFormatter(feed));
}

This also has a few additional advantages:

1. Unit tests can ensure the ActionResult is a FeedResult

2. Unit tests can examine the Feed property to examine results without parsing XML

3. Switching to Atom format involved just changing the new Rss20FeedFormatter to Atom10FeedFormatter.

HostForLIFE.eu ASP.NET MVC 6 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 :: How to Get Lookup Data in ASP.NET MVC 6?

clock April 12, 2019 12:28 by author Peter

In this article, I will explain about getting lookup dataa into you view ASP.Net MVC 6. This is a super common problem I encounter when building ASP.net MVC applications. I have a form that has a drop down box. Not only do I need to select the correct item from the edit model to pick from the drop down but I need to populate the drop down with the possible values.

Over the years I've used two approaches to doing this. The first is to push into the ViewBag a list of values in the controller action. That looks like
public ActionResult Edit(int id){ 
    var model = repository.get(id);

    ViewBag.Provinces = provincesService.List();

    return View(model);
}
Then in the view you can retrieve this data and use it to populate the drop down. If you're using the HTML helpers then this looks like

@Html.DropDownListFor(x=>x.province, (IEnumerable<SelectListItem>)ViewBag.Provinces)
This becomes somewhat messy when you have a lot of drop downs on a page. For instance consider something like

public ActionResult Edit(int id){ 
  var model = repository.get(id);

    ViewBag.Provinces = provincesService.List();
    ViewBag.States = statesService.List();
    ViewBag.StreetDirections = streetDirectionsService.List();
    ViewBag.Countries = countriesService.List();
    ViewBag.Counties = countiesService.List();

    return View(model);
}

The work of building up the data in the model becomes the primary focus of the view. We could extract it to a method but then we have to go hunting to find the different drop downs that are being populated. An approach I've taken in the past is to annotate the methods with an action filter to populate the ViewBag for me. This makes the action look like

[ProvincesFilter]
[StatesFilter]
[StreetDirectionsFilter]
[CountriesFilter]
[CountiesFilter]
public ActionResult Edit(int id){ 
  var model = repository.get(id);
  return View(model);
}

One of the filters might look like

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{
    var countries = new List<SelectListItem>();
    if ((countries = (filterContext.HttpContext.Cache.Get(GetType().FullName) as List<SelectListItem>)) == null)
    {
        countries = countriesService.List();
        filterContext.HttpContext.Cache.Insert(GetType().FullName, countries);
    }
    filterContext.Controller.ViewBag.Countries = countries;
    base.OnActionExecuting(filterContext);
}

This filter also adds a degree of caching to the request so that we don't have to keep bugging the database.

Keeping a lot of data in the view bag presents a lot of opportunities for error. We don't have any sort of intellisense with the dynamic view object and I frequently use the wrong name in the controller and view, by mistake. Finally building the drop down box using the HTML helper requires some nasty looking casting. Any time I cast I feel uncomfortable.

@Html.DropDownListFor(x=>x.province, (IEnumerable<SelectListItem>)ViewBag.Provinces)
Now a lot of people prefer transferring the data as part of the model; this is the second approach. There is nothing special about this approach you just put some collections into the model.

I've always disliked this approach because it mixes the data needed for editing with the data for the drop downs which is really incidental. This data seems like a view level concern that really doesn't belong in the view model. This is a bit of a point of contention and I've challenged more than one person to a fight to the death over this very thing.

So neither option is particularly palatable. What we need is a third option and the new dependency injection capabilities of ASP.net MVC open up just such an option: we can inject the data services directly into the view. This means that we can consume the data right where we retrieve it without having to hammer it into some bloated DTO. We also don't have to worry about annotating our action or filling it with junk view specific code.

To start let's create a really simple service to return states.

public interface IStateService 
{
    IEnumerable<State> List();
}

public class StateService : IStateService 
{
    public IEnumerable<State> List() {
        return new List<State>
        {
            new State { Abbreviation = "AK", Name = "Alaska" },
            new State { Abbreviation = "AL", Name = "Alabama" }
        };
    }
}

Umm, looks like we're down to only two states, sorry Kentucky.

Now we can add this to our container. I took a singleton approach and just registered a single instance in the Startup.cs.

services.AddInstance(typeof(IStateService), new StateService()); 
This is easily added the the view by adding

@inject ViewInjection.Services.IStateService StateService

As the first line in the file. Then the final step is to actually make use of the service to populate a drop down box:

<div class="col-lg-12"> 
        @Html.DropDownList("States", StateService.List().Select(x => new SelectListItem { Text = x.Name, Value = x.Abbreviation }))
</div> 

That's it! Now we have a brand new way of getting the data we need to the view without having to clutter up our controller with anything that should be contained in the view.

HostForLIFE.eu ASP.NET MVC 6 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.

 



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