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 :: ASP.NET MVC 5 Scaffolding

clock April 14, 2016 20:19 by author Anthony

ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. It makes it easy to add boilerplate code to your project that interacts with a data model.

In previous versions of Visual Studio, scaffolding was limited to ASP.NET MVC projects. With Visual Studio 2013, you can now use scaffolding for any ASP.NET project, including Web Forms. Visual Studio 2013 does not currently support generating pages for a Web Forms project, but you can still use scaffolding with Web Forms by adding MVC dependencies to the project. Support for generating pages for Web Forms will be added in a future update.

When using scaffolding, we ensure that all required dependencies are installed in the project. For example, if you start with an ASP.NET Web Forms project and then use scaffolding to add a Web API Controller, the required NuGet packages and references are added to your project automatically. To add MVC scaffolding to a Web Forms project, add a New Scaffolded Item and select MVC 5 Dependencies in the dialog window. There are two options for scaffolding MVC; Minimal and Full. If you select Minimal, only the NuGet packages and references for ASP.NET MVC are added to your project. If you select the Full option, the Minimal dependencies are added, as well as the required content files for an MVC project.

Support for scaffolding async controllers uses the new async features from Entity Framework 6.This Article shows how to use Scaffolding With your ASP.net MVC 5 Application.

Step 1 :

  • Let's create an ASP.net MVC 5 web application in Visual Studio 2013 and name it as ScaffoldingMVC5.

Scaffolding With ASP.net MVC 5

Step 2 :

  • Right click your Controllers folder and Add New Scaffolded Item is as below.

  • Scaffolding With ASP.net MVC 5


Step 3 :

  • From the Add Scaffold window, select the MVC 5 Controller with views,using Entity Framework scaffold template.

  • Scaffolding With ASP.net MVC 5

Step 4 :

  • The Add Controller window,you can give the name of your Controller (e.g. PetController),select your model class (e.g. Pet) and also you can create the Data context class (e.g. DataContext) as below. 
  • All other options are put as default.
  • After that click Add button.
  • When you click the New data context.. button  on Add Controller box above,it will pop up the below New Data Context box.
  • From there you can give a name for your Data context is as below.
  • e.g. DataContext

Scaffolding With ASP.net MVC 5


Step 5 :

  • The solution tree shows the relevant classes and pages were created for above example.
  • For example, the following image shows the MVC controller (i.e. PetController) and Views (i.e. Inside the Pet folder) that were created through scaffolding for a Model class named Pet.
  • Scaffolding With ASP.net MVC 5

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 4 Hosting - HostForLIFE.eu :: How to Create ASP.NET MVC 4 Web Registration?

clock April 13, 2016 21:39 by author Anthony

In this tutorial, I will explain how to develop web applications using C# ASP.NET MVC 4.  You’ll create an ASP.NET MVC 4 web application that allows the user to register their details.

Index View

  •     Page 1 will ask the user to enter their name. The page will have a “Next” button that shows page 2.
  •     Page 2 will ask the user for their details: username, password and email address.
  •     Page 3 will confirm the user’s details. The page will have a hyperlink to return to page 1.

Creating First Page


Create an empty ASP.NET MVC 4 web application named Registration using C#. Implement the first page, make sure to choose Empty Project and use the ASPX engine.

An MVC4 Applcation

  • Add a controller class named HomeController to the Controllers folder. To do this right-click and select Add>Controller from the context menu. Add a standard action method named Index() that returns the default view to this controller.In an MVC application all of the browser’s HTTP requests are handled first by a Controller class. This class contains action methods that the requests are directed to. The specific controller and method that is invoked will depend on the request’s URL.
  • Add an ASPX view for the Index() action method. To do this right-click in the Index() method and select Add View from the context menu, make sure to deselect “use a layout or masterpage” and use the ASPX Engine. This will cause a web page named Index.aspx to be added in the Views/Home folder.In an MVC application a view holds only the visual content of the web page.
  • Open Index.aspx in the Views\Home folder.
  • Add a tag, to start a form in Index.aspx.
  • Within the form, include the Html.TextBox() HTML helper function to display a text box named username. HTML helper functions make it easier to add HTML tags to a view by employing intellisense.
  • Add a submit button inside the form. Use plain old HTML to do this. The submit button will post back the form back to the same action and the same controller.
  • Use a %}%> tag to mark the end of the form.
    <body>
    <h3>Welcome to the website registration</h3>
    <%using(Html.BeginForm())
    {%>
    <%: Html.Label("Please enter your name") %>
    <%: Html.TextBox("name")%>
    <p> <input type="submit" value="Next" /> </p>
    <%}%>
    </body>
  • View code file.
  • Now run the application. When the page is shown, just enter your name and click the button. This submits the form back to the server, and causes MVC to call your Index() action method. Unfortunately Index() only redisplays page without your name. To solve this problem, you now need to handle the HTTP POST request so the user is redirected to the next page.
  • Edit the Index() method in the Controller so that it only handles the initial page request. To do this adds this annotation just above the method declaration. [HttpGet]
    [HttpGet]//Run action method on first request
    public ActionResult Index() {
    return View();
    }
  • Add a second action method also called Index(), to handle form submissions from the first page. To do this, add this annotation just above the method declaration.[HttpPost]
  • This method also requires a string parameter called username, which MVC automatically populates from the textbox on the page.
  • Now edit your new Index() method by including this statement.
    return RedirectToAction(“Details”, “Home”, new {name = name});
    This attempts to redirect the next page and it also passes the name parameter to that page.
    [HttpPost]//Run action method on form submission
    public ActionResult Index(string name)
    {
    return RedirectToAction("Details", "Home", new { name = name });
    }
  • View code file.
  • Run the application. Even though you will get a 404 Page Not Found error, this is not a problem at this stage. The error will disappear when you create the Details() action method and the Details.aspx view on the next lab.

Creating User Details Page

Add a model class to hold the user details. Add a view to allow the user to enter their details.

  • In the Models folder, create a class named UserDetails. To do this right-click and select Add>Class from the context menu.In an MVC application a Model class contains all the business, validation and data access code. Since the Model classes are clearly separate from the application’s Controllers and Views, they can be implemented, tested & maintained independently.
  • Add properties of type string for name, username, password and email address.
    public class UserDetails
    {
    public string Name { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string EmailAddress { get; set; }
    }
  • View code file.
  • In the controller class, add an action method named Details(). This handles HTTP GET requests to display the Details view.
  • Include a string parameter to hold the name in the Details() method. The parameter will be passed in from the first page.
  • Inside the method, create a new UserDetails object and set its Name property to the incoming name parameter.
  • Add this statement to return the default view: return View(user);
    [HttpGet]//Run action method on first request
    public ActionResult Details(string name)
    {
    UserDetails user = new UserDetails();
    user.Name = name;
    return View(user);
    }
  • View code file.
  • This passes an UserDetails object as the model parameter to the view.
  • Add an ASPX view for the Details() action method. Make the view a strongly-typed view, based on the UserDetails class. This will add a Web page named Details.aspx to the Views/Home folder.
  • Implement Details.aspx to display the name entered on the first page in a heading.
  • In Details.aspx also display a form containing text boxes. These allow the user to enter their details. Use Html.TextBoxFor() for each text box.
  • At the bottom of Details.aspx add a submit button.
    <body>
    <h3>Hi <%: Model.Name %></h3>
    Please enter your registration details
    <div>
    <% Html.EnableClientValidation(); %>
    <% using(Html.BeginForm())
    {%>
    <p>
    <%: Html.LabelFor(m => m.UserName, "User Name:")%>
    <%: Html.TextBoxFor(m => m.UserName)%>
    </p>
    <p>
    <%: Html.LabelFor(m => m.Password, "Password:")%>
    <%: Html.TextBoxFor(m => m.Password)%>
    </p>
    <p>
    <%: Html.LabelFor(m => m.EmailAddress, "Email Address:")%>
    <%: Html.TextBoxFor(m => m.EmailAddress)%>
    </p>
    <p> <input type="submit" value="Next" /> </p>
    <%}%>
    </div>
    </body>
  • View code file.
  • Back in the controller class, implement another action method named Details() to handle HTTP POST requests.
  • The method takes a UserDetails parameter. MVC will populate this object automatically with the data entered in each text box.
  • Return a view specifying “Confirmation” as the view name. Pass the UserDetails object as the model parameter to the view. The view does not yet exist.
    [HttpPost]//Run action method on form submission
    public ActionResult Details(UserDetails user)
    {
    return View("Confirmation", user);
    }
  • Run the application. In the first page, enter your name and click the submit button. Verify that the “user details” page now appears, displaying your name and a series of text boxes. Enter some details and then click the submit button. At this stage you will receive an ASP.NET error indicating the “Confirmation” view cannot be found. You will create this in the next lab.

Creating The Confirmation Page

Add a view to confirm the user has entered their details.

  • For the HTTP-POST version of the Details() action method, then add an ASPX view named Confirmation that is strongly bound to the UserDetails class. Make the view a strongly-typed view, based on the UserDetails class.
  • Implement Confirmation.aspx so that it shows the user information.
  • Add a hyperlink at the bottom of the page to return the user to the first page. Use the Html.ActionLink() helper function.
    <body>
    <div>
    <% using(Html.BeginForm())
    {%>
    <p>You have now been registered as:</p>
    <ul>
    <li> User Name: <%: Model.UserName %> </li>
    <li> Password: <%: Model.Password%> </li>
    <li> Email Address: <%: Model.EmailAddress %> </li>
    </ul>
    <p> <%: Html.ActionLink("Return to welcome page", "Index")%>
    </p>
    <%}%>
    </div>
    </body>
  • View code file.
  • Run the application. Is it now working fully?

Add Validation

Add validation checks when user details are entered.

  • Include validation in the model class. Add attributes to the properties that define the checks. Use attributes in the System.ComponentModel.DataAnnotations namespace, such as [Required], [StringLength], and [Range].
    [Required(ErrorMessage = "Name required")]
    public string Name { get; set; }
  • In the Details page, do not proceed if there are any validation errors.
    [HttpPost]//Run action method on form submission public
    ActionResult Details(UserDetails user)
    {
    if (ModelState.IsValid)
    return View("Confirmation", user);
    else
    return View(user);
    }
  • View code file.
  • Enable client-side validation In the Details page.

HostForLIFE.eu ASP.NET MVC 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to ASP.NET Tag Helper?

clock April 12, 2016 00:13 by author Anthony

In this tutorial, I will show you how to use tag helper in ASP.NET 5 MVC 6. A Tag Helper is just another c-sharp class that inherits from the abstract Microsoft.AspNet.Razor.TagHelpers.TagHelper class.  This abstract class contains two virtual methods for you: Process and ProcessAsync.

Adding Dependency

To be able to use MVC and his new feature called Tag Helper, we need to add some dependencies. Open the file and add 3 pieces project.json library

"dependencies": {
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta5",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5",
    "Microsoft.AspNet.Mvc": "6.0.0-beta5",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5",
    "Microsoft.AspNet.Tooling.Razor" : "1.0.0-beta5"
  },

Library Microsoft.AspNet.Mvc "used to be able to use MVC and Microsoft.AspNet.Mvc.TagHelpers and Microsoft.AspNet.Tooling.Razor library in order to use the Tag Helper.


Creating Folders

Create a new folder in the root of some of the project for the benefit of our MVC. There are 4 folders created are Models, Views, Controllers and Repository. Repository Folder optional course here, only I use to put the class file repository.

1. New Folder

Startup configuration

We are ready to perform the configuration in Startup.cs so dependency has been added. For the purposes of configuration, MVC needs to be added to the DI Container and to the pipeline. Therefore, the configuration will occur in the second method.

To register MVC to DI Container is easy, see the following code
public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc();
}

As for the register to the pipeline and conduct the default configuration routing is below

public void Configure(IApplicationBuilder app)
{
  app.UseMvc(route => {
    route.MapRoute("Default", "{Controller=Home}/{Action=Index}/{Id:int?}");
  });
}

Unlike earlier where we use an anonymous object in the third parameter to provide a default value in the template, now simply by using the = sign on the template that is the default value.

Else instead of using the fourth parameter to constraints in the form of regex we can directly use them in the template. In the example above there at {id: int?}. int id only intended to be integers.

The question mark (?) Means that the id is optional, there may be no.

MVC in Action

Until this stage, the configuration for MVC is ready and live Model, View and Controller as required. Example I had Controller as under
public class HomeController : Controller
{
  private StudentRepository _studentRepository = new StudentRepository();
 
  public IActionResult Index()
  {
    var students = _studentRepository.Get();
    return View(students);
  }
 
  public IActionResult Get(int id)
  {
    var student = _studentRepository.Get(id);
    return View(student);
  }
}


Now let's make her view by utilizing the new features that the Tag Helper.

At the root folder View create a MVC View Page with name Import _ViewImports.cshtml.

2. View Import

And enter the following line in it to be able to use the Tag Helper on all pages view.
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

I'll give you an example :

@{
    ViewBag.Title = "Home Page";
    Layout = "_Layout";
}
@using MiniTour.Models
@model List<Student>
 
<h3>Student List</h3>
<hr/>
 
<table>
    <tr>
        <th>First Name</th>
        <th>LastName</th>
        <th></th>
    </tr>
 
    @foreach (var s in Model)
    {
        <tr>
            <td>@s.FirstName</td>
            <td>@s.LastName</td>
            <td>@Html.ActionLink("Detail","Get","Home",new { id=s.Id}) |
                <a asp-controller="Home" asp-action="Get" asp-route-id="@s.Id">Detail</a></td>
        </tr>
    }
 
</table>

 


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 4 Hosting - HostForLIFE.eu :: How to Use KnockoutJS in ASP.NET MVC 4?

clock April 8, 2016 20:00 by author Anthony

In this post I’ll show how you can use KnockoutJS and SignalR together. KnockoutJS is a MVVM implementation for JavaScript written by Steve Sanderson, in my opinion the author of the best ASP.NET MVC textbooks available. Simply put it lets you bind a JavaScript object model to your HTML UI using a simple binding format, and when the underlying model is updated the UI is automatically updated to reflect the change.

SignalR is a library from Microsoft utilising HTML5’s WebSockets allowing server side code to call JavaScript functions on the client to create real-time functionality.

To me these two libraries seem like a match made in heaven. SignalR calling a JavaScript function to alter data, and Knockout automatically updating the UI.

To create real-time web application with little effort. I’m going to create a very basic example of a web page showing a list of exchange rates hooked up using KnockoutJS. I’ll then create a server side page to update the data and use SignalR to call a JavaScript function to update the JavaScript model.

Source code

The layout page looks like this.

<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
 
    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.css">
 
    <script src="~/Scripts/jquery-1.6.4.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery.signalR-1.0.0-rc2.js" type="text/javascript"></script>
    <script src="~/Scripts/knockout-2.2.1.debug.js" type="text/javascript"></script>
    <script src="~/Scripts/knockout.mapping-latest.debug.js" type="text/javascript"></script>
    <script src="/signalr/hubs" type="text/javascript"></script>
 
</head>
<body>
    <div class="container">
        @RenderBody()
    </div>
 
    @RenderSection("scripts", false)
</body>
</html>

You can see I’ve included references for SignalR, jQuery, Knockout and Knockout Mapping (I’ll explain what this is and how to use it later). You’ll also see a reference to signalr/hubs. This gets generated on the fly by SignalR to manage the client connection, but you still need to create a reference to it.

Now I want to create a view to display my currencies with Knockout. I have created a HomeController with an Index view that looks like this:

<h2>Current Exchange Rates</h2>
 
<table class="table table-bordered">
    <thead>
        <tr>
            <th></th>
            <th>USD</th>
            <th>EUR</th>
            <th>GBP</th>
            <th>INR</th>
            <th>AUD</th>
            <th>CAD</th>
            <th>ZAR</th>
            <th>NZD</th>
            <th>JPY</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>USD</th>
            <!-- ko foreach: currencies -->
            <td data-bind="text: price"></td>
            <!-- /ko -->
        </tr>
    </tbody>
</table>

It’s just a basic table with some bindings for Knockout. Knockout supports several types of bindings and other functions; if you haven’t already run through the live examples it’s worth doing. Above I’m using the for foreach binding to iterate though a collection on the model called currencies. Bindings can be applied to a HTML element, for example to the tbody element to make each item create a table row. In my example I only want one row and I’m manually adding the text USD to the first column, so I’m using the containerless syntax using comment tags. For each item in my collection it will render a TD tag and bind the price property of the object as the text.

That’s my template all set up and ready to go. Now for adding the JavaScript to bind my model to my UI.

var currentCurrencies = [
                { code: "USD", price: ko.observable(1.00000) },
                { code: "EUR", price: ko.observable(0.75103) },
                { code: "GBP", price: ko.observable(0.63163) },
                { code: "INR", price: ko.observable(53.8253) },
                { code: "AUD", price: ko.observable(0.95095) },
                { code: "CAD", price: ko.observable(1.00020) },
                { code: "ZAR", price: ko.observable(9.04965) },
                { code: "NZD", price: ko.observable(1.18616) },
                { code: "JPY", price: ko.observable(89.3339) }
            ];
 
            var currencyModel = function (currencies) {
                this.currencies = currencies;
            };
 
            ko.applyBindings(currencyModel(currentCurrencies));

First I have created an array of currency objects. For each price I have used the ko.observable function which is required for knockout to track the property and automatically update the UI. I have created a simple model with a property called currencies, and then used ko.applyBinding passing the model which binds to the template. I get a basic table that looks like this:

Knockout

At this point if I were to use JavaScript to update the price of one of the objects in the currencies collection the UI would automatically update to reflect that change. I’m now going to do that, but using SignalR to call the JavaScript function.

I’m going to create a page that allows me to update the currencies server side, so I have created a C# model called CurrencyViewModel which looks like this:

public class CurrencyViewModel
{
    public class Currency
    {
        [JsonProperty(PropertyName = "code")]
        public string Code { get; set; }
        [JsonProperty(PropertyName = "price")]
        public decimal Price { get; set; }
    }
 
    public List Currencies { get; set; }
}

You’ll notice the JsonProperty attribute for each property in the Currency object. Later when I call the JavaScript function the Currency object will be serialised as Json and passed into the method, so I added the attribute to make the property names lowercase to fit with JavaScript coding standards.

Next I’ve created an AdminController with an Index method to manage the currencies:
[HttpGet]
public ActionResult Index()
{
    var viewModel = new CurrencyViewModel()
    {
        Currencies = CurrencyService.GetCurrencies()
    };
 
    return View(viewModel);
}

CurrencyService is just an object returning a static list of currency objects. This could be coming from a database or file etc. Later I’ll show how you can also use SignalR to call server side code, and I’ll call this GetCurrencies method to populate the initial exchange rates instead of using the JavaScript array. The CurrencyService object looks like this.

public class CurrencyService
{
    public static List GetCurrencies()
    {
        return new List()
                    {
                        new CurrencyViewModel.Currency() {Code = "USD", Price = 1.00000M},
                        new CurrencyViewModel.Currency() {Code = "EUR", Price = 0.75103M},
                        new CurrencyViewModel.Currency() {Code = "GBP", Price = 0.63163M},
                        new CurrencyViewModel.Currency() {Code = "INR", Price = 53.8253M},
                        new CurrencyViewModel.Currency() {Code = "AUD", Price = 0.95095M},
                        new CurrencyViewModel.Currency() {Code = "CAD", Price = 1.00020M},
                        new CurrencyViewModel.Currency() {Code = "ZAR", Price = 9.04965M},
                        new CurrencyViewModel.Currency() {Code = "NZD", Price = 1.18616M},
                        new CurrencyViewModel.Currency() {Code = "JPY", Price = 89.3339M}
                    };
    }
}

Now I have created a couple of EditorTemplate to allow me to update the currencies. I’ll omit the markup from this post but you can see them in the provided source code. This gives me a form to edit my rates:

Knockout

Okay, so now it’s time to use SignalR. The first step is to register the necessary routes in the Global.asax Application_Start method:

RouteTable.Routes.MapHubs();

Next I need to create a hub. A hub is a C# class containing methods that the client can call. When you run the application, SignalR will create the hubs JavaScript file I mentioned earlier based on the C# hubs in your application. This is essentially a proxy allowing the client to connect to the hub and for messages to flow from server to client and vice versa.

All hubs must inherit from the abstract Hub class. I have a CurrencyHub which looks like this:

public class CurrencyHub : Hub
{
    public void GetCurrencies()
    {
        Clients.Caller.setCurrencies(CurrencyService.GetCurrencies());
    }
}

Methods in the hub are available to the client. As I mentioned earlier I will later get the currencies for the initial load from the currency service, so that is what this GetCurrencies method is for. You do not need to add methods to your hub to call functions on the client.

I’m now going to implement the post action for the Index method on my AdminController. This is where I will call the client side JavaScript to update the exchange rates directly to the UI:

[HttpPost]
public ActionResult Index(CurrencyViewModel viewModel)
{
    var context = GlobalHost.ConnectionManager.GetHubContext<CurrencyHub>();
    viewModel.Currencies.ForEach(c => context.Clients.All.updateCurrency(c.Code, c.Price));
    return View(viewModel);
}

Once I have this I can use Clients.All to call a JavaScript function on all clients connected to the hub. All is dynamic so you simply add a method matching that of the JavaScript function with the same signature. Here that function is called updateCurrency and code and price are passed as arguments.

My action method is looping through each currency object in the model’s collection and calling updateCurrency for each. Not the most efficient way to do it in the real world, but I’m trying to keep this example simple.

Now for the JavaScript to hook it all up. Knockout isn’t dependent on any other library, but SignalR uses jQuery so I’ve now wrapped everything in a ready function. First off I’ve added an updateCurrency method to my model which finds the given currency and updates the price. This is using Knockout’s arrayFirst utilitymethod. The remaining changes set up SignalR. First I create a reference to my currency hub then start the connection to the hub. Next I set up the updateCurrency function on hub.client which is the function that will be called from the server. From this function I’m just calling the function on my model to update the correct price.

$(function () {
    var currentCurrencies = [
        { code: "USD", price: ko.observable(1.00000) },
        { code: "EUR", price: ko.observable(0.75103) },
        { code: "GBP", price: ko.observable(0.63163) },
        { code: "INR", price: ko.observable(53.8253) },
        { code: "AUD", price: ko.observable(0.95095) },
        { code: "CAD", price: ko.observable(1.00020) },
        { code: "ZAR", price: ko.observable(9.04965) },
        { code: "NZD", price: ko.observable(1.18616) },
        { code: "JPY", price: ko.observable(89.3339) }
    ];
 
    var currencyModel = function (currencies) {
        this.currencies = currencies;
 
        this.updateCurrency = function (code, price) {
            var currency = ko.utils.arrayFirst(this.currencies, function (currency) {
                return currency.code == code;
            });
 
            currency.price(price);
        };
    };
 
    ko.applyBindings(currencyModel(currentCurrencies));
 
    var hub = $.connection.currencyHub;
 
    $.connection.hub.start();
 
    hub.client.updateCurrency = function (code, price) {
        updateCurrency(code, price);
    };
});

And that’s all there is to it. My server side code calls hub.client.updateCurrency which calls the method of the same name in the model. That method finds the correct currency and updates the price. As price is observable Knockout then automatically updates the UI.

The final thing I’m going to do is load the currencies from the server when opening the page. This could be done using an ajax request, but you can also do it with SignalR. I’ll be calling the method in my CurrencyHub which I briefly mentioned earlier in the post. Here it as again:

public void GetCurrencies()
{
    Clients.Caller.setCurrencies(CurrencyService.GetCurrencies());
}

The method doesn’t accept any arguments, and when called, it calls a JavaScript function on the client that made the call to the server. This is through Clients.Caller, rather than Clients.All which I used earlier. The JavaScript can now be amended as below to first load the data from the server using SignalR.

$(function () {
    var currencyModel = function (currencies) {
        this.currencies = ko.mapping.fromJS(currencies);
 
        this.updateCurrency = function (code, price) {
            var currency = ko.utils.arrayFirst(this.currencies(), function (currency) {
                return currency.code() == code;
            });
 
            currency.price(price);
        };
    };
 
    var hub = $.connection.currencyHub;
 
    $.connection.hub.start().done(function () {
        hub.server.getCurrencies();
    });
 
    hub.client.updateCurrency = function (code, price) {
        updateCurrency(code, price);
    };
 
    hub.client.setCurrencies = function (currentCurrencies) {
        ko.applyBindings(currencyModel(currentCurrencies));
    };
});

The first obvious change is that I’m using the done function on hub.start so that once the connection has started it calls the getCurrencies function on the server. The function on the server was in pascal case, but when calling via JavaScript you need to use camel case.

The next change is that I’ve moved the ko.applyBindings call inside the setCurrencies function. This is the function called by the server which passes the collection of Currency objects. These objects are serialised as Json, so currentCurrencies here is an array of JavaScript objects that represent the currencies. This is that passed into my model when doing the binding.

As this is just an array of plain objects, none of the properties are observable, so the UI won’t be updated if they change. You could easily manually parse the array and re-create the objects as observable, but here I’m using the Knockout Mapping plugin. The plugin takes a JavaScript object and returns an object with observable properties. It has overrides that allow you to take control of some of the mapping, but here I’m just using the default implementation with ko.mapping.fromJS. As I’m passing in an array, it will return an observable array, where each property of each object in the array is also observable.

Due to this there are a couple of other changes required. One line 6 this.currencies becomes this.currencies(). Any observable object requires parenthesis to access as it’s converted to a method. Similarly on line 7 this.code becomes this.code() for the same reason. Previously I didn’t make code observable, so I didn’t need parenthesis, but as this time I used the mapping plugin it’s now observable.

 

 

HostForLIFE.eu ASP.NET MVC 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 4 Hosting - HostForLIFE.eu :: How to Make ASP.NET MVC 4 Web Application?

clock April 7, 2016 23:39 by author Anthony

In this tutorial I will show you how to make ASP.NET MVC 4 Web Application for beginners. But before we start, we need an application which enables user to create/update/read/delete (CRUD) the data connected with cars. Let’s create a new project.

  • Open Visual Studio 2012
  • File/New/Project -> select Web/ASP.NET MVC 4 Web Application.
  • When new window appears, please select a template as Internet Application and the vie engine as Razor. For this example, please do not select Create a unit test project.
  • Confirm


Your project structure should look like this:

1

We will start from creating a new model class. To do this, please right click on folder Models, select Add->New Item and choose Class. Name it as Car.cs – it is our first POCO in a project. The next thing is to add primitive properties inside of a class as below:

2

This class represents a Car. Car is an object which will be stored in a Cars table in a database. It means, that one car = one row in a db.

If you have already created this class, please create another one for model, named CarContext.cs -> here we will include DbSet for our Car objects and information about the name of the future database. To add it, please follow steps from Car.cs. The structure of CarContext is shown below:

9

The next thing is to add a Controller for our Model. It will store Create, Read, Update, Delete methods. To add this please right click at Controller, then select Add->Controller:

4

Click Add.  As you can see, VS 2012 has automatically added CarController with implemented CRUD methods and also new views:

5

The last thing to do is to add a connection string into web.config file. To do this, please open web.config and add this connection string:

6

Name of connection string should be the same in CarContext class ( : base(“Cars”) ).

Please hit F5 to Debug. When new tab appears please insert http://localhost:yourport/car/ and enter. This will open the view folder named Car, where all razor files for CRUD methods are stored. After that you should see your web application.

The next step is to click Create New. The new View will appear (Create.cshtml). Just add a new car with its brand and model name. After that you will see the list of all cars that have been already added. You can edit this, delete or show the details.

 

HostForLIFE.eu ASP.NET MVC 4 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Get Started With React Using TypeScript and ASP.NET MVC 6?

clock April 4, 2016 20:18 by author Anthony

All of the major frameworks (Web API, forms, and MVC) have been rolled out under the umbrella of a single unified programming model. There’s a new built-in dependency framework, and there are Tag Helpers. All this has had a major impact on development. A lot has changed in the world of ASP.NET 5 and MVC 6. But In this tutorial, I will explain about how to get started with React using TypeScript and ASP.NET 5 MVC 6.

But before we start, there are few things you will need to install :

  • Microsoft Visual Studio 2015 (Community Edition is free and it’s open source!)
  • TypeScript (included in VS2015)
  • Node.js and NPM (included in VS2015


    Deprecated, use Typings:
  • Typings. Run npm install typings -g to install globally.
  • Webpack. Run npm install webpack -g to install globally.

 

Create a New ASP.NET MVC 6 Project

First create a new ASP.NET Web Application project. In the next dialog choose Empty template under ASP.NET 5 Templates. This is to keep things simple and we will only be adding add the stuff we actually need.

Install ReactJS.NET

Next you’ll need to modify your project.json file so open it up. To work with React in .NET we’ll be using a library called ReactJS.NET. It will allow you to do server side (or isomorphic) rendering which is cool but more on that later.

Before installing ReactJS.NET we’ll need to remove "dnxcore50": { } line from project.json to make it work. Then add "React.AspNet": "2.1.2" and "Microsoft.AspNet.Mvc": "6.0.0-rc1-final" under dependencies and save the file. Both ASP.NET MVC 6 and ReactJS.NET should get immediately installed.

Your project.json should now look something like this:

{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "React.AspNet": "2.1.2"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  },

  "frameworks": {
    "dnx451": { }
  },

  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ]
}


Create a new folder called app under your project. This is where we’ll be hosting all our React components. Right-click that folder and add a new item. Search for a TypeScript JSX file template and name your file HelloWorld.tsx. Add the following lines.

/// <reference path="../../../typings/main/ambient/react/index.d.ts" />
import React = require('react');

// A '.tsx' file enables JSX support in the TypeScript compiler,
// for more information see the following page on the TypeScript wiki:
// https://github.com/Microsoft/TypeScript/wiki/JSX

interface HelloWorldProps extends React.Props<any> {
    name: string;
}

class HelloMessage extends React.Component<HelloWorldProps, {}> {
    render() {
        return <div>Hello {this.props.name}</div>;
    }
}
export = HelloMessage;

You’ll see that the react.d.ts cannot be resolved. To fix this you’ll need to run typings install react --ambient --save in the Package Manager console to install the TypeScript definitions for react. Visual Studio will still complain about the --module flag that must be provied. To fix this add a tsconfig.json in the app folder with the following content:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "jsx": "preserve"
  }
}

Note : If the JSX isn’t being generated make sure that you have enabled TypeScript compilation in Visual Studio. To do this check the Automatically compile TypeScript files which are not part of the project under Tools -> Options -> TypeScript -> Project -> General in Visual Studio.

 

Set Up Web Pack

We’ll be using Webpack although you could use any other module bundler as well. You should have installed Webpack already but if you haven’t check out the beginning of this post on how to do it.

In the app folder create index.js:

module.exports = {
    // All the components you'd like to render server-side
    HelloMessage: require('./HelloWorld')
};

This will be used to tell Webpack which components to bundle together for server and client side rendering. Right now we only have the HelloWorld component.

Next in your wwwroot folder add two files called client.js and server.js. They both share the same content for this project:


// All JavaScript in here will be loaded client/server -side.
// Expose components globally so ReactJS.NET can use them
var Components = require('expose?Components!./../app');

The last thing that’s left is a Webpack configuration file. Create webpack.config.js under your project:

var path = require('path');
module.exports = {
    context: path.join(__dirname, 'wwwroot'),
    entry: {
        server: './server',
        client: './client'
    },
    output: {
        path: path.join(__dirname, 'wwwroot/build'),
        filename: '[name].bundle.js'
    },
    module: {
        loaders: [
            // Transform JSX in .jsx files
            { test: /\.jsx$/, loader: 'jsx-loader?harmony' }
        ],
    },
    resolve: {
        // Allow require('./blah') to require blah.jsx
        extensions: ['', '.js', '.jsx']
    },
    externals: {
        // Use external version of React (from CDN for client-side, or
        // bundled with ReactJS.NET for server-side)
        react: 'React'
    }
};


Webpack will need some additional modules to do the bundling. Right-click the project and select “Add item”. In the dialog choose NPM Configuration file and name it package.json:

{
    "version": "1.0.0",
    "name": "ASP.NET",
    "private": true,
    "devDependencies": {
        "webpack": "1.12.9",
        "expose-loader": "0.7.1",
        "jsx-loader": "0.13.2"
    }
}


Once again saving the file will execute NPM and install the three packages.

Finally open command prompt and browse to the project’s folder (where webpack.config.js is located). Then type webpack, press enter and Webpack should beautifully build two JavaScript bundles under wwwroot/build. Of these client.bundle.js should be included client side and server.bundle.js should be included server side. Remember to run webpack each time you have modified your React components or add this step to your build process.

Add a controller and a view

Next, do the obvious thing of creating a controller and a view so that we can host our fancy React component somewhere. Create a folder called Controllers under the project and add a new controller called HomeController under the folder. The controller should have only one GET Index method like so:

using Microsoft.AspNet.Mvc;
namespace React.MVC6.Sample.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
    }
}

After that add a folder called Views under the project. Under Views add a new folder called Shared. Create a layout file called _Layout.cshtml there with the following content:

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Then add a few defaults for our views. In the Views folder add a new file called _ViewImports.cshtml with just the following content. This will ensure that ReactJS.NET is by default available in all our views.

@using React.AspNet


Create another file called _ViewStart.cshtml under Views folder with this content:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Finally create a new folder called Home under Views and create a file called Index.cshtml in there. Place the following in there to render your React component with initial data:

@{
    ViewBag.Title = "Index";
}

<h1>Hello World</h1>

@Html.React("Components.HelloMessage", new { name = "Sam" })

<script src="https://fb.me/react-0.14.0.min.js"></script>
<script src="https://fb.me/react-dom-0.14.0.min.js"></script>
<script src="@Url.Content("/build/client.bundle.js")"></script>

@Html.ReactInitJavaScript()

Including the javascripts in the view like this isn’t very pretty but you’ll get the idea. The name that we pass to the component could as well come from a model passed down from the controller.

Configure the Web Application

Then we will need to make sure that ASP.NET MVC 6 and React get loaded properly when the application starts up. So open up your startup.cs file and replace the contents with this:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using React.AspNet;

namespace React.MVC6.Sample
{
    public class Startup
    {
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddReact(); // Add React to the IoC container
            services.AddMvc();
        }

        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.UseIISPlatformHandler();

            // Initialise ReactJS.NET. Must be before static files.
            app.UseReact(config =>
            {
                config
                    .SetReuseJavaScriptEngines(true)
                    .AddScriptWithoutTransform("~/build/server.bundle.js");
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                ServeUnknownFileTypes = true
            });

            app.UseMvc(r =>
            {
                r.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" }
                );
            });
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}

 

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: ASP.NET MVC 5 Custom Filter

clock April 1, 2016 21:37 by author Anthony

UNDERSTANDING ASP.NET MVC

ASP.NET MVC is the implementation of the MVC architecture to the programming framework. ASP.NET physically is library consisting of some assembly that can be installed on top .NET Framework 3.5. ASP.NET MVC was created as an option for developers who like MVC architecture. ASP.NET MVC did not replace Web Forms architecture that has been known and used by developers ASP.NET. The main components of ASP.NET MVC still the same as the basic architecture of MVC, the Model, View, and Controller. Some of the additional component is a web server, Routing, and dispatchers. Web server always bridging the interaction between the user with a web program. We can use the IIS web server, or a personal web server as long as the program is still in the development phase. IIS versions that can be used vary from version 5 to version 7.

ASP.NET MVC 5 Provides five different kinds of Filters. They are :

  • Authentication
  • Authorization
  • Action
  • Result
  • Exception

Filters are used to inject logic at the different levels of request processing. Let us understand where at the various stages of request processing different filters get applied. Authentication Authorization filter runs after the filter and before any other filter or action method. Action filter runs before and after any action method. Result filter runs before and after execution of any action result. Exception filter runs only if action methods, filters or action results throw an exception.

An action filter consists of codes that run either before or after an action runs. It can be used for tasks like logging, privileged based authorization, authentication, caching etc. Creating a custom action filter is very easy. It can be created in four simple steps:

  • Create a class
  • Inherit ActionFilterAttribute class
  • Override the OnActionExecuting method to run logic before the action method
  • Override the OnActionExecuted method to run logic after the action method

The purpose of the action filter is to find whether a logged in user belongs to a particular privileges or not. On the basis of the result, a user will access a particular action or navigate to the login action. To do this, I have created a class and extended the ActionFilterAttribute class.

using PrivilegeDemo.Services;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using System.Web.Routing;
 
namespace PrivilegeDemo.Filters
{
    public class AuthorizationPrivilegeFilter : ActionFilterAttribute
    {
      
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
         
            AuthorizationService _authorizeService = new AuthorizationService();
            string userId = HttpContext.Current.User.Identity.GetUserId();
            if (userId != null)
            {
                var result = _authorizeService.CanManageUser(userId);
                if (!result)
                {
 
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary{{ "controller", "Account" },
                                          { "action", "Login" }
 
                                         });
                }
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary{{ "controller", "Account" },
                                          { "action", "Login" }
 
                                         });
 
            }
            base.OnActionExecuting(filterContext);
        }
 
 
    }
}

 

The OnActionExecuting method is overridden because we want the code to execute before the action method gets executed. Once the action filter is created, it can be used in three ways:

  • As Global filter
  • As Controller
  • As Action

By adding a filter to the global filter in App_Start\FilterConfig it will be available globally to the entire application.

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
           filters.Add(new AuthorizationPrivilegeFilter());
        }
    }

By adding a filter to a particular Controller it will also be available to the all actions of that particular controller.

[AuthorizationPrivilegeFilter]
    public class HomeController : Controller
    {

Adding a filter to a particular action it will be available to the particular action.

[AuthorizationPrivilegeFilter]
        public ActionResult About()
        {

 

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Make ASP.NET MVC 5 Run in Ubuntu?

clock March 31, 2016 18:04 by author Anthony

ASP.NET is a programming framework to create web application server side. ASP.NET using C # code is well structured so it is easy to understand and repair. C # also provides a variety of code hint, hint error before the code is executed. C # is executed using JIT system, so it may be able to run faster than interpreted languages like PHP.

But until a few years ago ASP.NET can only run on windows platform. Because there are some who still is Microsoft's patents, these projects difficult to run optimally and tend to be limited compatibility, even dotGNU project to a halt in 2012. So today I will discuss about how to run ASP.NET MVC 5 on Ubuntu Linux.

Before that some things need to be prepared, such as:

  • Computers with 14:04 LTS Ubuntu operating system.
  • ASP.NET MVC 5 that has been published.
  • Internet connection.

How to Make ASP.NET MVC 5 Run in Ubuntu?

  • Make sure that your operating system has been updated by running the following command:
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install apache2 package by running the command:
    sudo apt-get install apache2
  • Input Mono into the system package list, this needs to be done so that the mono version that will be installed up to date. make sure you run the code below line by line.
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" | sudo tee -a /etc/apt/sources.list.d/mono-xamarin.list
    sudo echo "deb http://download.mono-project.com/repo/debian alpha main" | sudo tee /etc/apt/sources.list.d/mono-xamarin-alpha.list
    sudo apt-get update && sudo apt-get dist-upgrade
  • Install mono-complete package
    sudo apt-get install mono-complete
  • Install libapache2-mod-mono package
    sudo apt-get install libapache2-mod-mono
    sudo a2enmod mod_mono_auto
  • Set apache2, so that the apache2 folder using mono. This procedure must be repeated for each new application
    sudo nano /etc/apache2/sites-available/testasp.conf
  • Copy-paste the following lines into the console, adjust the path and name if necessary. click ctrl + o, enter the ctrl + x to save the file.
    Alias /testasp "/var/www/html/testasp"
    MonoServerPath inventory "/usr/bin/mod-mono-server4"
    MonoDebug inventory true
    MonoSetEnv inventory MONO_IOMAP=all
    MonoApplications inventory "/testasp:/var/www/html/testasp"
    <Location "/testasp">
    Allow from all
    Order allow,deny
    MonoSetServerAlias inventory
    SetHandler mono
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip dont-vary
    </Location>
    <IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript
    </IfModule>

  • Create a new folder in the / var / www / html / testasp, adjust permissions folder if necessary. Asp.net files will be stored here.
    sudo mkdir /var/www/html/testasp
  • Enable configuration site that have been created.
    sudo a2ensite testasp
    sudo service apache2 restart
  • Upload or copy the files you want to run ASP.NET MVC into the folder / var / www / html / testasp.
  • Test sites in the browser, adjust your url with IP engine.
  • Done. You have been successfully run ASP.NET MVC 5 on the Linux operating system.

 

HostForLIFE.eu ASP.NET MVC 5 Hosting
HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24x7 access to their server and site configuration tools. Plesk completes requests in seconds. It is included free with each hosting account. Renowned for its comprehensive functionality - beyond other hosting control panels - and ease of use, Plesk Control Panel is available only to HostForLIFE's customers. They
offer a highly redundant, carrier-class architecture, designed around the needs of shared hosting customers.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create & Update Cookie in ASP.NET MVC?

clock March 30, 2016 23:25 by author Peter

Today, we will explain you about how to create and update cookie in ASP.NET MVC. An HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie), is a small piece of data sent from a website and stored in the user's web browser while the user is browsing. Every time the user loads the website, the browser sends the cookie back to the server to notify the user's previous activity. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). Cookies can also store passwords and form content a user has previously entered, such as a credit card number or an address.

The output of the index.aspx runs over the Home Controller:
public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        string cookie = "There is no cookie!";
        if(this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            cookie = "Yeah - Cookie: " + this.ControllerContext.HttpContext.Request.Cookies["Cookie"].Value;
        }
        ViewData["Cookie"] = cookie;
        return View();
    }

Here it is detected if a cookie exists and if yes than it will be out given.
These two Links guide you to the CookieController:
public class CookieController : Controller
{

    public ActionResult Create()
    {
        HttpCookie cookie = new HttpCookie("Cookie");
        cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();

        this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        return RedirectToAction("Index", "Home");
    }

    public ActionResult Remove()
    {
        if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
        {
            HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
            cookie.Expires = DateTime.Now.AddDays(-1);
            this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
        }
        return RedirectToAction("Index", "Home");
    }

}


With the create method it´s quite simple to create a Cookie and lay it down into the response and afterwards it turns back to the Index View.

The remove method controls if a cookie exists and if the answer is positive the Cookie will be deleted directly.

Beware while deleting cookies:
This way to delete a cookie doesn´t work:
this.ControllerContext.HttpContext.Response.Cookies.Clear();


The cookie has to go back to the remove (like it is given in the Cookie Controller) and an expiry date should be given. I´m going to set it on yesterday so the browser has to refuse it directly.

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 5 Hosting - HostForLIFE.eu :: How to Create ASP.NET MVC 5 Page

clock March 29, 2016 18:31 by author Anthony

Here we will give an example of how to create ASP.NET MVC 5 page with examples, they can be seen on ASP.NET MVC framework to be displayed on the web browser. We are going on to describe some things about the basics of ASP.NET MVC that should be known.

You need to know what is included on the MVC Pattern Architectural Pattern. And software design pattern that is used in ASP.NET MVC is Front Controller, which means that the control will be concentrated in a class alone. While ASP.NET Web Forms is different because it has a controller on each page.

Here's how the MVC, can be seen in the following figure

 

In ASP.NET MVC 5, the address will be written in the address bar on your web browser does not show as physical files, because of the configuration and routing processes that can be seen in Global.asax.cs and RouteConfig.cs file (folder App_start).

Global.asax file can also be found on the project ASP.NET Web Forms, this file serves as an application file that is responsible for the events at the application level is raised by ASP.NET or HttpModules. At the time the application is run, namely on Application_Start method, can be seen there are file event handling. Then it can be seen on these methods belong to the class RouteConfig. Here is the content of the class RouteConfig residing on file in the folder App_Start RouteConfig.cs.

It can be seen that the name of the default controller is used in this application is Home. This means that if you follow the code needs to be created with the name of the Home controller class, and then save it in a folder Controllers.

To add this class please right click on the folder and select Add Controller > Controller

Select the MVC Controller 5 - Empty and then click the Add button.

It will display a window Add Controller that serves to give the name of the controller class that will be created. For example, assign a name to the Home Controller Controller name column, then click the Add button.

Here is the content of the class controller of HomeController that have been made :

Then make special view for HomeController class in Home folder with index.cshtml. Then right click on the Home folder, then choose Add > New Item. After that, Choose MVC 5 View Page, give a name as you desire, click Add button.

Then you can modify Index.cshtml file like this :

You can try it on your web browser, then this will be the result

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