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 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 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.



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