European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting United Kingdom - HostForLIFE.eu :: Compressing an ASP.NET MVC Response Manually

clock December 19, 2019 04:21 by author Peter

This post is regarding compression your http result while not using IIS Dynamic Compression. And this is code to compress ASP.NET MVC 6 Response Manually:

using System;
using System.IO.Compression;
using System.Web;
namespace WebCompressionSample
{
    public static class ResponseCompressor
    {
        public static void Compress(HttpContext context)
        {
           {
               return;
            }
            string acceptEncoding = context.Request.Headers["Accept-Encoding"];
            if (string.IsNullOrEmpty(acceptEncoding))
            {
                return;
            }
            if (acceptEncoding.IndexOf("gzip",
                StringComparison.OrdinalIgnoreCase) > -1)
            {
                       context.Response.Filter = new GZipStream(
                       context.Response.Filter, CompressionMode.Compress);
                       context.Response.AppendHeader("Content-Encoding", "gzip");

            }
            else if (acceptEncoding.IndexOf("deflate",
                StringComparison.OrdinalIgnoreCase) > -1)
            {
                    context.Response.Filter = new DeflateStream(
                    context.Response.Filter, CompressionMode.Compress);
                   context.Response.AppendHeader("Content-Encoding", "deflate");
            }
        }
    }
}

Well, this shows a way to do the compression itself. Looking on however you are doing ASP.NET MVC, you most likely can call it otherwise.In my case, I referred to as it manually from an ASP.NET Webforms PageMethod (more on why below), however if you're using ASP.NET MVC for instance, you most likely wish to wrap it in an ActionFilter and apply that to the action you wish to compress its output. Let me apprehend within the comments or on twitter if you've got a problem implementing it in a particular situation.

IIS 7+ has built in dynamic compression support (compressing output of server-side scripts like ASP.NET, PHP, etc.). It’s not by default as a result of compression dynamic content means that running the compression for each request (because it doesn’t know what the server-side script can generate for each request, the purpose of using server-side programming is generating dynamic content).

Static compression on the opposite side (caching static files like styles and scripts) is on by default as a result of once the static resource is compressed, the compressed version is cached and served for each future request of an equivalent file (unless the file changes of course). I’d say if your server side scripts expect to come large text-based content (say, large data, even when paging, etc. like large reports or whatever), always turn dynamic compression on, a minimum of for the pages that expect to come massive data sets of text.

In several cases though the majority of huge files will be scripts (and probably images) will be the larger components though, which are usually taken care of (for scripts for example) by IIS static compression or ASP.NET Bundling.



Free ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create a Star Rating in ASP.NET MVC

clock May 29, 2015 06:41 by author Rebecca

Members rating plays a vital role in deciding whether a product or services should be bought or not. In this article, you are going to learn how to create a star rating system in ASP.NET MVC.

Database structure

There are two small changes needed in our database for this rating system

1.  Add a field called "Votes" (or "Rating" whatever best suits you) in the existing database table where we are going to save other data of the post.

2. Add another database table called "VoteLog" that will save each vote details. Below are details of each field of this table.

  • AutoId - auto increment
  • SectionId - id of different sections of the website (we might be interested in implementing this rating system in multiple sections of the website, so all rating details will be saved into this database table)
  • VoteForId - unique id of the record for which member has rated
  • UserName - username of the member who has rated
  • Vote - rate given by a member for this post
  • Active -whether this record is active and should be counted

Different status of Rating control

Status 1 - When a visitor is visiting the website

Status 2 - When a visitor has logged in (is a member of the website)

Status 3 - After rating the post

Status 4 - When a visitor had rated the post and coming back to the same post again and browser cookie is still present in visitors' machine.

Status 5 - When a visitor had voted and browser cookies are cleared and he/she tried to vote again for the same post.

Lets start to create the Star Rating system

Step 1

Create a partial view named _VoteNow.cshtml in the Views/Shared folder and copy-paste below code.

@model string
@{
    var url = Request.Url.AbsolutePath;   
}
@if (!User.Identity.IsAuthenticated)
{
    <text>Please <a href="/Account/[email protected]" title="Login to rate">Login</a> to rate</text>
    return;
}
@if (Request.Cookies[url] == null) {
    <div id="ratingDiv" class="smallText"> Poor
        <img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="1" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="2" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="3" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="4" /><img src="/images/whitestar.gif" alt="" class="ratingStar" data-value="5" /> Excellent
        <label id="lblResult"></label>
    </div>
    <style type="text/css">
        .ratingStar {
            cursor:pointer;
        }
    </style>
    <script type="text/javascript">
        var clickedFlag = false;
        $(".ratingStar").mouseover(function () {
            $(this).attr("src", "/images/yellowstar.gif").prevAll("img.ratingStar").attr("src", "/images/yellowstar.gif");
        });
        $(".ratingStar, #radingDiv").mouseout(function () {
            $(this).attr("src", "/images/whitestar.gif");
        });
        $("#ratingDiv").mouseout(function () {
            if (!clickedFlag)
            {
                $(".ratingStar").attr("src", "/images/whitestar.gif");
            }
        });
        $(".ratingStar").click(function () {
            clickedFlag = true;
            $(".ratingStar").unbind("mouseout mouseover click").css("cursor", "default");

            var url = "/Home/SendRating?r=" + $(this).attr("data-value") + "&s=5&id=@Model&url=@url";
            $.post(url, null, function (data) {
                $("#lblResult").html(data);
            });
        });
        $("#lblResult").ajaxStart(function () {
            $("#lblResult").html("Processing ....");
        });
        $("#lblResult").ajaxError(function () {
            $("#lblResult").html("<br />Error occured.");
        });
    </script>
}else{
    <text><span style="color:green;">Thanks for your vote !</span></text>
}


Step 2

Create a SendRating action method in HomeController.

public JsonResult SendRating(string r, string s, string id, string url)
        {
            int autoId = 0;
            Int16 thisVote = 0;
            Int16 sectionId = 0;
            Int16.TryParse(s, out sectionId);
            Int16.TryParse(r, out thisVote);
            int.TryParse(id, out autoId);
           
            if (!User.Identity.IsAuthenticated)
            {
                return Json("Not authenticated!");
            }

            if (autoId.Equals(0))
            {
                return Json("Sorry, record to vote doesn't exists");
            }

            switch (s)
            {
                case "5" : // school voting
                    // check if he has already voted
                    var isIt = db.VoteModels.Where(v => v.SectionId == sectionId &&
                        v.UserName.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) && v.VoteForId == autoId).FirstOrDefault();
                    if (isIt != null)
                    {
                        // keep the school voting flag to stop voting by this member
                        HttpCookie cookie = new HttpCookie(url, "true");
                        Response.Cookies.Add(cookie);
                        return Json("<br />You have already rated this post, thanks !");
                    }

                    var sch = db.SchoolModels.Where(sc => sc.AutoId == autoId).FirstOrDefault();
                    if (sch != null)
                    {
                        object obj = sch.Votes;

                        string updatedVotes = string.Empty;
                        string[] votes = null;
                        if (obj != null && obj.ToString().Length > 0)
                        {
                            string currentVotes = obj.ToString(); // votes pattern will be 0,0,0,0,0
                            votes = currentVotes.Split(',');
                            // if proper vote data is there in the database
                            if (votes.Length.Equals(5))
                            {
                                // get the current number of vote count of the selected vote, always say -1 than the current vote in the array
                                int currentNumberOfVote = int.Parse(votes[thisVote - 1]);
                                // increase 1 for this vote
                                currentNumberOfVote++;
                                // set the updated value into the selected votes
                                votes[thisVote - 1] = currentNumberOfVote.ToString();
                            }
                            else
                            {
                                votes = new string[] { "0", "0", "0", "0", "0" };
                                votes[thisVote - 1] = "1";
                            }
                        }
                        else
                        {
                            votes = new string[] { "0", "0", "0", "0", "0" };
                            votes[thisVote - 1] = "1";
                        }

                        // concatenate all arrays now
                        foreach (string ss in votes)
                        {
                            updatedVotes += ss + ",";
                        }
                        updatedVotes = updatedVotes.Substring(0, updatedVotes.Length - 1);

                        db.Entry(sch).State = EntityState.Modified;
                        sch.Votes = updatedVotes;
                        db.SaveChanges();

                        VoteModel vm = new VoteModel()
                        {
                            Active = true,
                            SectionId = Int16.Parse(s),
                            UserName = User.Identity.Name,
                            Vote = thisVote,
                            VoteForId = autoId
                        };
                       
                        db.VoteModels.Add(vm);
                       
                        db.SaveChanges();

                        // keep the school voting flag to stop voting by this member
                        HttpCookie cookie = new HttpCookie(url, "true");
                        Response.Cookies.Add(cookie);
                    }
                    break;
                default:
                    break;
            }
            return Json("<br />You rated " + r + " star(s), thanks !");
        }

Step 3

Now, it's time to display current rating. Create _VoteShow.cshtml partial view in the Views/Shared folder and copy-paste below code.

@model string

@{
    Single m_Average = 0;

    Single m_totalNumberOfVotes = 0;
    Single m_totalVoteCount = 0;
    Single m_currentVotesCount = 0;
    Single m_inPercent = 0;
    var thisVote = string.Empty;
   
    if (Model.Length > 0)
    {
        // calculate total votes now
        string[] votes = Model.Split(',');
        for (int i = 0; i < votes.Length; i++)
        {
            m_currentVotesCount = int.Parse(votes[i]);
            m_totalNumberOfVotes = m_totalNumberOfVotes + m_currentVotesCount;
            m_totalVoteCount = m_totalVoteCount + (m_currentVotesCount * (i + 1));
        }

        m_Average = m_totalVoteCount / m_totalNumberOfVotes;
        m_inPercent = (m_Average * 100) / 5;

        thisVote = "<span style=\"display: block; width: 65px; height: 13px; background: url(/images/starRating.png) 0 0;\">" +
            "<span style=\"display: block; width: "+ m_inPercent + "%; height: 13px; background: url(/images/starRating.png) 0 -13px;\"></span> " +
            "</span>" +
            "<span class=\"smallText\">Overall ratings: <span itemprop=\"ratingCount\">" + m_totalNumberOfVotes + "</span> | Rating: <span itemprop=\"ratingValue\">" + m_Average.ToString("##.##") + "</span> out of 5 </span>  ";
    }
}
 <div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
    <meta itemprop="bestRating" content="5" />
    <meta itemprop="worstRating" content="1">
    <meta itemprop="ratingValue" content="@m_Average.ToString("##.##") %>" />
      @Html.Raw(thisVote)
  </div>

Step 4

Calling rating controls (partial vies) on the post page.

<div class="tr" style="background-color:#f1f1f1;">
                <div class="td0">Please rate this school</div>
                <div class="td">@Html.Partial("_VoteNow", Model.AutoId.ToString())</div>
                <div class="td">@Html.Partial("_VoteShow", Model.Votes)</div>
            </div>


While calling _VoteNow, we are passing the unique post id as parameter and while calling _VoteShow, we are passing current votes (Rates) in the form of  "x,x,x,x,x" as parameter and here is the final output displays on the web page.

Done! Your own rating system is up and live!

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create Cache Profiles in ASP.NET MVC

clock May 25, 2015 06:02 by author Rebecca

In this tutorial, I will tell you about creating Cache Profiles. To cache the data returned by Index() action method for 60 seconds, we would use [OutputCache] attribute as shown below:

[OutputCache(Duration=60)]
public ActionResult Index()
{
    return View(db.Employees.ToList());
}

In the example above, the OutputCache settings are specified in code. The disadvantage of this approcah is that:
1. If you have to apply the same cache settings, to several methods, then the code needs to be duplicated.
2. Later, if we have to change these cache settings, then we need to change them at several places. Maintaining the code becomes complicated. Also, changing the application code requires build and re-deployment.

To overcome these disadvantages, cache settings can be specified in web.config file using cache profiles:

Step 1

Specify cache settings in web.config using cache profiles:
<system.web>
  <caching>
    <outputCacheSettings>
      <outputCacheProfiles>
        <clear/>
        <add name="1MinuteCache" duration="60" varyByParam="none"/>           
      </outputCacheProfiles>
    </outputCacheSettings>
  </caching>
</system.web>


Step 2

Reference the cache profile in application code:
[OutputCache(CacheProfile = "1MinuteCache")]
public ActionResult Index()
{
    return View(db.Employees.ToList());
}


The cache settings are now read from one central location i.e from the web.config file. The advantage of using cache profiles is that:
1. You have one place to change the cache settings. Mantainability is much easier.
2. Since the changes are done in web.config, we need not build and redeploy the application.

Using Cache profiles with child action methods:
[ChildActionOnly]
[OutputCache(CacheProfile = "1MinuteCache")]
public string GetEmployeeCount()
{
    return "Employee Count = " + db.Employees.Count().ToString()
        + "@ " + DateTime.Now.ToString();
}


When Cache profiles are used with child action methods, you will get an error:

- Duration must be a positive number.

There colud be several ways to make cache profiles work with child action methods. The following is the approach, that I am aware of. Please feel free to leave a comment, if you know of a better way of doing this.

How to create a custom OutputCache attribute that loads the cache settings from the cache profile in web.config:

Step 1

Right click on the project name in solution explorer, and add a folder with name = Common

Step 2

Right click on "Common" folder and add a class file, with name = PartialCacheAttribute.cs

Step 3

Copy and paste the following code. Notice that, I have named the custom OutputCache attribute as PartialCacheAttribute:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;

namespace MVCDemo.Common
{
    public class PartialCacheAttribute : OutputCacheAttribute
    {
        public PartialCacheAttribute(string cacheProfileName)
        {
            OutputCacheSettingsSection cacheSettings =                 (OutputCacheSettingsSection)WebConfigurationManager.GetSection("system.web/caching/outputCacheSettings");
            OutputCacheProfile cacheProfile = cacheSettings.OutputCacheProfiles[cacheProfileName];
            Duration = cacheProfile.Duration;
            VaryByParam = cacheProfile.VaryByParam;
            VaryByCustom = cacheProfile.VaryByCustom;
        }
    }
}

Step 4

Use PartialCacheAttribute on the child action method, and pass it the name of the cache profile in web.config. Please note that, PartialCacheAttribute is in MVCDemo.Common namespace.
[ChildActionOnly]
[PartialCache("1MinuteCache")]
public string GetEmployeeCount()
{
    return "Employee Count = " + db.Employees.Count().ToString()
        + "@ " + DateTime.Now.ToString();
}

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Entity Framework to Insert, Update and Delete Data in ASP.NET MVC

clock May 22, 2015 07:01 by author Rebecca

In this tutorial, I will tell you about selecting, inserting, updating and deleting data in mvc using entity framework. I will be using tables tblDepartment and tblEmployee for this tutorial.

Step 1

First you must run the sql script to create and populate these tables, here is the example:

Create table tblDepartment
(
 Id int primary key identity,
 Name nvarchar(50)
)

Insert into tblDepartment values('IT')
Insert into tblDepartment values('HR')
Insert into tblDepartment values('Payroll')

Create table tblEmployee
(
 EmployeeId int Primary Key Identity(1,1),
 Name nvarchar(50),
 Gender nvarchar(10),
 City nvarchar(50),
 DepartmentId int
)

Alter table tblEmployee
add foreign key (DepartmentId)
references tblDepartment(Id)

Insert into tblEmployee values('Mark','Male','London',1)
Insert into tblEmployee values('John','Male','Chennai',3)
Insert into tblEmployee values('Mary','Female','New York',3)
Insert into tblEmployee values('Mike','Male','Sydeny',2)
Insert into tblEmployee values('Scott','Male','London',1)
Insert into tblEmployee values('Pam','Female','Falls Church',2)
Insert into tblEmployee values('Todd','Male','Sydney',1)
Insert into tblEmployee values('Ben','Male','New Delhi',2)
Insert into tblEmployee values('Sara','Female','London',1)

Step 2

Create a new asp.net mvc 4 web application. Then Right click on the "Models" folder and add "ADO.NET Entity Data Model". Set Name = EmployeeDataModel.edmx.

On the subsequent screen, select "Generate from database" option and click "Next". On "Choose your data connection screen", click on "New Connection" button. Specify the sql server name. In my case, I have sql server installed on my local machine. So I have set "Server Name=(local)". From "Select or enter a database name" dropdownlist, select the Database name and click "OK". Then Click "Next".

Step 3

On "Choose your database objects" screen, expand "Tables" and select "tblDepartment" and "tblEmployee" tables. Set "Model Namespace=Models" and click "Finish".

At this point we should have tblDepartment and tblEmployee entities generated.
a) Change tblDepartment to Department
b) Change tblEmployee to Employee
c) Change tblEmployees nvigation property to Employees
d) Change tblDepartment nvigation property to Department

Step 4

Right click on the "Controllers" folder and select Add - Controller. Then, Set:
Name = EmployeeController
Template = MVC controller with read/write actions and views, using Entity Framework
Model class = Employee(MVCDemo.Models)
Data Context Class = EmployeeContext(MVCDemo.Models)
Views = Razor

Finally click "Add".

At this point you should have the following files automatically added.
1. EmployeeController.cs file in "Controllers" folder
2. Index, Create, Edit, Detail and Delete views in "Employee" folder.

On Create and Edit views, please delete the following scripts section. We will discuss these in a later video session.
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


At this point, if you run the application by pressing CTRL + F5, you will get an error stating - The resource cannot be found. This is because, by default, the application goes to "HOME" controller and "Index" action.

To fix this,
1. Open "RouteConfig.cs" file from "App_Start" folder
2. Set Controller = "Employee"

Run the application again. Notice that, all the employees are listed on the index view. We can also create a new employee, edit an employee, view their full details and delete an employee as well.

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc.



Free ASP.NET MVC 6 Hosting UK – HostForLIFE.eu :: How to Creating Routes with ASP.NET MVC 6

clock April 29, 2015 08:01 by author Peter

In this tutorial, I will show you how to create routes with ASP.NET MVC 6. When using MVC 6, you don’t create your Route collection yourself.

You let MVC create the route collection for you. And now, write the following code:
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace RoutePlay
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }
}

The ConfigureServices() method is utilized to enroll MVC with the Dependency Injection framework built into ASP.NET 5. The Configure() system is utilized to register MVC with OWIN. This is what my MVC 6 ProductsController resembles:

Notice that I have not configured any routes. I have not utilized either tradition based or property based directing, yet I don't have to do this. If I enter the request “/products/index” into my browser address bar then I get the response “It Works!”:

When you calling the ApplicationBuilder.UseMvc() in the Startup class, the MVC framework will add routes for you automatically. The following code will show you, what the framework code for the UseMvc() method looks like:
public static IApplicationBuilder UseMvc([NotNull] this IApplicationBuilder app)
{
    return app.UseMvc(routes =>
    {
    });
}
public static IApplicationBuilder UseMvc(
    [NotNull] this IApplicationBuilder app,
    [NotNull] Action<IRouteBuilder> configureRoutes)
{
    // Verify if AddMvc was done before calling UseMvc
    // We use the MvcMarkerService to make sure if all the services were added.    MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);
    var routes = new RouteBuilder
   {
        DefaultHandler = new MvcRouteHandler(),
        ServiceProvider = app.ApplicationServices
    };
     configureRoutes(routes);
     // Adding the attribute route comes after running the user-code because
    // we want to respect any changes to the DefaultHandler.
    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
        routes.DefaultHandler,
        app.ApplicationServices));
     return app.UseRouter(routes.Build());
}


The AttributeRouting.CreateAttributeMegaRoute() does all of the heavy-lifting here (the word “Mega” in its name is very appropriate). The CreateAttributeMegaRoute() method iterates through all of your MVC controller actions and builds routes for you automatically.
Now, you can use convention-based routing with ASP.NET MVC 6 by defining the routes in your project’s Startup class. And here is the example code:
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
namespace RoutePlay
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }
       public void Configure(IApplicationBuilder app)
        {
            app.UseMvc(routes =>
            {
                // route1
                routes.MapRoute(
                    name: "route1",
                    template: "super",
                    defaults: new { controller = "Products", action = "Index" }
                );
                // route2
                routes.MapRoute(
                    name: "route2",
                    template: "awesome",
                    defaults: new { controller = "Products", action = "Index" }
                );
            });
        }
    }
}


I hope this tutorial works for you!

Free ASP.NET MVC Hosting
Try our Free ASP.NET MVC Hosting today and your account will be setup soon! You can also take advantage of our Windows & ASP.NET Hosting support with Unlimited Domain, Unlimited Bandwidth, Unlimited Disk Space, etc. You will not be charged a cent for trying our service for the next 3 days. Once your trial period is complete, you decide whether you'd like to continue.



ASP.NET MVC 6 Hosting UK - HostForLIFE.eu :: Working with CDN Bundle Config in ASP.NET MVC

clock November 25, 2014 08:20 by author Peter

At this moment, I will tell you about working with CDN bundle config in ASP.NET MVC 6. ASP.NET MVC includes nice attributes and Bundling is part of them. The Bundling and Minification attributes let you scale back quantity of HTTP requests that the web site wants in order to make by combining individual scripts and style sheet files. Additionally it may scale back a general scale bundle by minifying the content material of software. From ASP.NET MVC 4 bundling also contains CDN assistance also where one can utilize public CDN accessible for typical libraries. Let’s look this attributes in particulars.

Libraries such as jQuery, jQuery UI and a few some other libraries are commonly utilized in a lot of the applications. There will be accessible in CDN (Content Delivery Networks) specifying the URL of specific library along with particular version. Bundling now has CDN path as parameter in default bundle functionality where one can specify the path from the CDN library and utilize that. Thus whenever you application operate in production environment first it'll verify regardless of whether CDN can be found or otherwise in case accessible and then it can load it coming from the CDN itself and In case CDN isn't accessible and then it can load files hosted on server. CDN will use the distributed network when enabled, and in optimization mode. You can’t combine multiple CDN’s together (you can only use 1 script). By default. UseCdn is set to false.

And First, you need to Enable UseCdn feature:
bundles.UseCdn = true;

Now, Add the jQuery Bundle from the CDN Bundle with the code bellow:
var jqueryBundle = new ScriptBundle("~/bundles/jquery", "http://code.jquery.com/jquery-2.0.3.min.js").Include(
                "~/Scripts/jquery-{version}.js");
            jqueryBundle.CdnFallbackExpression = "window.jquery";
            bundles.Add(jqueryBundle);


The CdnFallbackExpression is used when even CDN server is unavailable. And next step, this is CDN bundle config:

bundles.UseCdn = true;
            var jqueryBundle = new ScriptBundle("~/bundles/jquery", "http://code.jquery.com/jquery-2.0.3.min.js").Include(
                "~/Scripts/jquery-{version}.js");
            jqueryBundle.CdnFallbackExpression = "window.jquery";
            bundles.Add(jqueryBundle);



ASP.NET MVC 6 Hosting Germany - HostForLIFE.eu :: How To Combine Angular.js with ASP.NET MVC?

clock November 21, 2014 05:31 by author Peter

Angular is a superb resource, however it took me a few time to identify a method to combine it elegantly along with ASP.NET MVC. This is essentially how I made it happen. First, you must build a new ASP.NET MVC app. Next step, install the Angular package through NuGet. Now for the customization.

The goal is to make use of the normal ASP. NET MVC navigation, unless for certain URLs, when we will permit Angular get over. So, http://www.yourdomain.com/Account/Login could be managed by ASP. NET (" ASP.NET-mode "), however http://www.yourdomain.com/#/Customers could be dealt with by Angular (" Angular-mode "). In fact, it is ASP.NET serving us the Customers page, however after that, we wish to use Angular for data-binding, navigation, routing, the forms, and so on.

Add a new Controller along with one method, Index (), which returns View (). Standard ASP. NET up till currently. I named mine AngularController.Next, add a View inside the corresponding folder (in my case :/Angular/Index. cshtml). During this view, found out your primary Angular view. Some thing such as:
@{
    ViewBag.Title = "Index";

<div ng-app="app">
    <div ng-controller="main as vm">
        <div ng-view class="shuffle-animation"></div>
    </div>
</div> 
@section scripts {
    @Scripts.Render("~/bundles/angular")
}

Now, when I am in "Angular-mode", I want my ASP.NET MVC include with Angular scripts. The Angular bundle looks something such as: (in /App_Start/BundleConfig.cs):
bundles.Add(new Bundle("~/bundles/angular").Include(
                      "~/Scripts/angular.js",
                      "~/Scripts/angular-animate.js",
                      "~/Scripts/angular-route.js",
                      "~/Scripts/angular-sanitize.js",
                      "~/Scripts/app/app.js",
                      "~/Scripts/app/config.js",
                      "~/Scripts/app/main.js",
                      "~/Scripts/app/customers/customers.js"));


The explanation I am not using a ScriptBundle is because we don't need ASP.NET to minify the Angular scripts. This leads to errors as a result of Angular generally depends on function arguments being certain strings.

In the meantime, minification is not necessary, however inside a production-environment, you'd need to make use of the minified Angular scripts. In app.js, config. js and main. js, I have place the required code to obtain Angular running. The most significant component is the getRoutes function in config.js :
function getRoutes() {
    return [
        {
            url: '/customers',
            templateUrl: '/Scripts/app/customers/customers.html'
        }
    ];
}


Finally, the customers.html and customers.js include my Angular logic and HTML markup for that particular page. This currently lets you navigate to http://localhost:1578/Angular/#/ (your portnumber may differ of course).

There you've it. ASP.NET MVC is serving the HTML page which contains references to Angular scripts and templates, the browser downloads everything, after which Angular wires all of it along (In fact, you may wish to configure ASP. NET to make use of a totally different URL to the AngularController)

Adding the following code with your navigation is as easy as adding this tag within your _Layout. cshtml file:
<li><a href="https://www.blogger.com/Angular/#/customers">Customers</a></li>

Do not forget the hash. Next, lets add a second page. This'll build the distinction in among what I have been calling " ASP. NET-mode " and " Angular-mode " more clear. Add a new html file and also a new javascript file onto the/Scripts/app/customers/folder, add the route to config. js and add the javascript file in the Angular bundle in BundleConfig. cs. The link inside my case might currently be :
<a href="https://www.blogger.com/Angular/#/customers/create">Create new customer</a>

Next step, whenever you operate the app, navigating from/Angular/#/customers to, say,/Account/Login can load the complete new page. However navigating from/Angular/#/customers to/Anguler/#/customers/create stays inside Angular, and merely loads the new template, " staying within " your SPA. You are able to sort of notice as a result of loading a new page " within " the SPA feels faster. So, we have effectively combined ASP. NET MVC along with Angular.js, allowing us to select where we want/need that.

 



ASP.NET MVC 6 Hosting with Paris (France) Server - HostForLIFE.eu :: Fixing Cached Values when Update Posted Form Values on Postback with ASP.MVC

clock November 18, 2014 08:56 by author Peter

While focusing on a project I encountered a wierd issue on my ASP.NET MVC 6. I produced an easy registration form which posted to my controller method, that obtained a view design like a parameter. Inside my method I had the need to update the values for this View Model prior to passing it to the user through a similar View. But, this really is exactly in which I encountered " strange " outcomes. Regardless of the correct data binding, correct code updating the design values, and also the correct design becoming passed straight into the view, front-end users still obtained the recent form values they initially posted.

This was initially puzzling, because I can notice the model I'd been passing in was the right way up to date. Initially I assumed it was actually some type of caching issue and tried numerous choices, however to no avail. Eventually I found out the matter was coming coming from the Razor Helper I'd been utilizing - specifically the EditorFor method (though this relates to any Razor helper method).

Let us have a closer look. Below is an easy registration view :
@model  posting.Controllers.Guest
 <h2>Register</h2>
 <p>Welcome...</p>
@using (Html.BeginForm())
{
    <table>
        <tr>
            <td>
                @Html.LabelFor(g => g.FirstName)
            </td>
            <td>
                @Html.EditorFor(g => g.FirstName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(g => g.LastName)
            </td>
            <td>
                @Html.EditorFor(g => g.LastName)
            </td>
        </tr>
        <tr>
            <td>
                @Html.LabelFor(g => g.Highlight)
            </td>
            <td>
                @Html.EditorFor(g => g.Highlight)
            </td>
        </tr>
    </table>
    <input type="submit" />
}

Now, I set up 2 simple controller methods to demonstrate that error. public ActionResult Register()
{
      return View();
}
[HttpPost]
public ActionResult Register(Guest guest)
{
    guest.FirstName = "Peter";
    return View(guest);

}

The first register method is really a Get request that will returns a simple sign up form using a first name and last name. The 2nd method will be the Post version from the first methodology, which means the values our user enters directly into form are certain to get mapped to our Guest view model. For demonstration purposes, I'm changing all users' names to Peter. But, when you operate this and fill out the form, you may notice the name never comes again as Peter - it constantly comes again as no matter what the user entered. The explanation for right here is the EditorFor helper method. These helper ways retrieve their information from ModelState first, then due to model object which is passed in. ModelState is essentially metadata in regards to the current model assigned from the MVC Model Binder when a request is mapped into your controller. Therefore in case the ModelState presently has values mapped from the MVC Model Binder, Razor Helpers can use those. The answer to get this is easy.
[HttpPost]
public ActionResult Register(Guest guest)
{
    ModelState.Remove("FirstName");
    guest.FirstName = "Peter";
    return View(guest);
}

That is literally all we need to do - this'll eliminate the FirstName property value set from the default MVC Model Binder and permit our personal code to write down a whole new value. You may also clear out the complete ModelState directly, as noticed beneath :
[HttpPost]
public ActionResult Register(Guest guest)
{
    ModelState.Remove("FirstName");
    guest.FirstName = "Peter";
    return View(guest);
}

This is a very simple issue however could be terribly frustrating in case you do not know what is happening.



ASP.NET MVC 6 Hosting with Paris (France) Server - HostForLIFE.eu :: Creating Calendar using ASP.NET MVC, Entity Framework and jQuery

clock November 14, 2014 05:22 by author Peter

Now, I we are going to learn how to create an  Event Calendar using ASP.NET MVC 6, Entity Framework and jQuery Fullcalendar plugin. First thing, that you have to do is Install the full calendar plugin using the Nuget Package Manager with the following command:

Install-Package jQuery.Fullcalendar

After that you'll be able to either add the scripts inside the BundleConfig. cs or you could reference all of these immediately in the _Layout. cshtml page (Master Page)
//Calendar css file
            bundles.Add(new StyleBundle("~/Content/fullcalendarcss").Include(
                     "~/Content/themes/jquery.ui.all.css",
                     "~/Content/fullcalendar.css"));
            //Calendar Script file
            bundles.Add(new ScriptBundle("~/bundles/fullcalendarjs").Include(
                      "~/Scripts/jquery-ui-1.10.4.min.js",
                      "~/Scripts/fullcalendar.min.js"));
@ViewBag.Title - My ASP.NET Application
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/fullcalendarcss")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/fullcalendarjs")


Currently Determine the full calendar in the Home/Index.cshtml page. We really need to outline the calendar along with page identity therefore build a div with all the id “calendar”
<div id=”calendar”></div>

Then, you must add the code below, in the Home controller:
public ActionResult GetEvents(double start, double end)
        {
            var fromDate = ConvertFromUnixTimestamp(start);
            var toDate = ConvertFromUnixTimestamp(end);
            //Get the events
            //You may get from the repository also
            var eventList = GetEvents();
            var rows = eventList.ToArray();
            return Json(rows, JsonRequestBehavior.AllowGet);
        }
        private List GetEvents()
        {
            List eventList = new List();
            Events newEvent = new Events{
                id = "1",
                title = "Event 1",
                start = DateTime.Now.AddDays(1).ToString("s"),
                end = DateTime.Now.AddDays(1).ToString("s"),
                allDay = false
            };
            eventList.Add(newEvent);
            newEvent = new Events
            {
                id = "1",
                title = "Event 3",
                start = DateTime.Now.AddDays(2).ToString("s"),
                end = DateTime.Now.AddDays(3).ToString("s"),
                allDay = false
            };
            eventList.Add(newEvent);
            return eventList;       
}      
private static DateTime ConvertFromUnixTimestamp(double timestamp)
        {          
            var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return origin.AddSeconds(timestamp);
        }
Now, Make an Events class under the Models folder:
public class Events
    {
        public string id { get; set; }
        public string title { get; set; }
        public string date { get; set; }
        public string start { get; set; }
        public string end { get; set; }
        public string url { get; set; }
        public bool allDay { get; set; }
    }

Then Add the code below to your page:

@section scripts{
<script type=”text/javascript”>// <![CDATA[
$(document).ready(function () {
$('#calendar').fullCalendar({
theme: true,

defaultView: 'agendaDay',
editable: false,
events: "/home/getevents/"
});
});
// ]]></script>
}



European ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Duplicate Controller Names in ASP.NET MVC Areas ?

clock November 11, 2014 07:02 by author Peter

By convention, ASP.NET MVC 6 applications use HomeController to discuss with the controller that handles requests created to the root of the application. this can be designed by default with the subsequent route registration:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

If you choose to partition your application using the ASP.NET MVC Areas feature, it’s commonplace that you simply would need calls to the root of every space to be handled employing a similar convention, via a HomeController.  However, if you add a HomeController to a part (for instance, an Admin area), you'll find yourself faced with this exception:

Multiple types were found that match the controller named ‘Home’. This can happen if the route that services this request (‘{controller}/{action}/{id}’) does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the ‘MapRoute’ method that takes a ‘namespaces’ parameter.

The request for ‘Home’ has found the following matching controllers:
AreaDemo.Areas.Admin.Controllers.HomeController
AreaDemo.Controllers.HomeController

Unfortunately by default you can not have duplicate controller names in ASPNET MVC Areas (or between a part and also the root of the application). fortunately, the fix for this can be pretty easy, and also the exception describes the step you wish to require.  Once you’ve added a part, you may have 2 completely different places (by default) wherever routes are defined: one in your root application and one in your area registration. you may need to regulate each of them to specify a namespace parameter. the root registration will change to one thing like this:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new string[] {"AreaDemo.Controllers"}
);

Likewise, at intervals the AdminAreaRegistration.cs class, the default RegisterArea methodology feels like this:
public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional}
        );
}

To adjust it to support a default HomeController and namespaces, it ought to be updated like so:
public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { controller="Home", action = "Index", id = UrlParameter.Optional},
        new string[] {"AreaDemo.Areas.Admin.Controllers"}
        );
}

With that changes in place, you must currently be ready to support the HomeController convention at intervals your MVC Areas, with duplicate controller names between areas and also the root of the applying.



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