European ASP.NET MVC Hosting

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

ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How To Create Area?

clock April 28, 2016 20:59 by author Anthony

Today, you will learn how to create Area in MVC 5. In MVC 5 (Visual Studio 2013), Area option can be found under ‘Add Scaffold’ dialog. In this post, I will take you through step by step to setup and running Area in MVC 5.


As you know MVC Architecture separates all the logics: model logic, business logic and presentation logic and provides a very clean and light weight application in total. One more good thing that I love is, it provides logical separation physically also. In physical logic separation controllers, models and views are kept in another folder on root with the help of Area. Areas provide a way to separate a large MVC Web Application into smaller functional groupings inside MVC Application and each group contains MVC Structure (Ex. Model, View and Controller folders). Area was introduced with MVC 2 release.

Assume, you are working on a MVC Project where you have a requirement  to develop various sections like account section, administrative section, support section, billing section and so on. Area is the best choice here, it will provide a strong physical structure as well as better code manageability. See how it looks like.

 


You can see every section has MVC Architecture Controller, Model, View (view will have a Shared folder where you can place your layouts, partial views etc) and an AreaRegistration (which contains RegisterArea method very similar to RegisterRoutes).

How to Create It

We are going to create CRUD views for Employee inside Area. We will take the advantage of EF Code First. Let’s walk through the simple steps. In Visual Studio 2012 IDE (MVC 4), we just right click on Project | Add | Area to create Area.

 

Step 1


Right click on Project and then select Add | Scaffold | MVC 5 Area.

Step 2

When we click on ‘Scaffold’ it opens a dialog where we need to select MVC 5 Area and hit on Add button, it will ask to enter area name, type ‘Admin’ and hit Add.
Do the same to add Area for Billing and Support, at the end we will have following structure.



 

Now once we are done with adding areas, go to next step.

Step 3


In above step we added three Areas, in each area we will find a class file areanameAreaRegistration.cs file, open this file, we will find following RegisterArea method inside class which inherits AreaRegistration class.

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Billing_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}


Look at this root closely, we will find this route begins with Admin and then controller, action and id (which is marked as optional).


We will find same thing in other Area also.

In total we have three areanameAreaRegistration.cs classes all inherits AreaRegistration class, and also a route defined for the Area. These routes should be registered inside Application_Start() method of Global.asax file, here is the code.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}


Now, let’s go in next step where we will create CRUD views and see how it opens in browser.


Step 4


Once we have done with previous steps, just go ahead and add model, controller and views to see how area opens in browser. We could and anything we want but just to keep things simple I am going to create a CRUD in Admin Area for Employee, here is the model I will be using.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

Now, create CRUD views and browse it.

Look at the URL in above image you will see the first segment ‘Admin’ is area name, second segment ‘Employee’ is controller, third segment ‘Details’ is action result and fourth segment ‘1’ is ID.


So, you can see how Area is working in MVC 5. There is no difference in ‘Area in MVC 4’ and ‘Area in MVC 5’, things are still same, the only change is the way Area added, that’s it.

 

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.

http://aspnetmvceuropeanhosting.hostforlife.eu/image.axd?picture=2015%2f10%2fhostforlifebanner.png



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: How to Handle ASP.NET MVC 5 Errors?

clock April 27, 2016 23:38 by author Anthony

Custom error pages and global error logging are two elementary and yet very confusing topics in ASP.NET MVC 5.

There are numerous ways of implementing error pages in ASP.NET MVC 5 and when you search for advice you will find a dozen different StackOverflow threads, each suggesting a different implementation.

Overview

What is the goal?


Typically good error handling consists of:

  • Human friendly error pages
    • Custom error page per error code (e.g.: 404, 403, 500, etc.)
    • Preserving the HTTP error code in the response to avoid search engine indexing
  • Global error logging for unhandled exceptions

Error pages and logging in ASP.NET MVC 5


There are many ways of implementing error handling in ASP.NET MVC 5. Usually you will find solutions which involve at least one or a combination of these methods:

  • HandleErrorAttribute
  • Controller.OnException Method
  • Application_Error event
  • CustomErrors element in web.config
  • httpErrors element in web.config
  • Custom HttpModule

All these methods have a historical reason and a justifyable use case. There is no golden solution which works for every application. It is good to know the differences in order to better understand which one is applied best.

Before going through each method in more detail I would like to explain some basic fundamentals which will hopefully help in understanding the topic a lot easier.

ASP.NET MVC Fundamentals


The MVC framework is only a HttpHandler plugged into the ASP.NET pipeline. The easiest way to illustrate this is by opening the Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
Navigating to the implementation of HttpApplication will reveal the underlying IHttpHandler and IHttpAsyncHandler interfaces:

public class HttpApplication : IComponent, IDisposable, IHttpAsyncHandler, IHttpHandler
ASP.NET itself is a larger framework to process incoming requests. Even though it could handle incoming requests from different sources, it is almost exclusively used with IIS. It can be extended with HttpModules and HttpHandlers.

HttpModules are plugged into the pipeline to process a request at any point of the ASP.NET life cycle. A HttpHandler is responsible for producing a response/output for a request.

IIS (Microsoft's web server technology) will create an incoming request for ASP.NET, which subsequently will start processing the request and eventually initialize the HttpApplication (which is the default handler) and create a response:

IIS, ASP.NET and MVC architecture

The key thing to know is that ASP.NET can only handle requests which IIS forwards to it. This is determined by the registered HttpHandlers (e.g. by default a request to a .htm file is not handled by ASP.NET).

And finally, MVC is only one of potentially many registered handlers in the ASP.NET pipeline.

This is crucial to understand the impact of different error handling methods.

Breaking down the options


HandleErrorAttribute

The HandleErrorAttribute is an MVC FilterAttribute, which can be applied to a class or a method:

namespace System.Web.Mvc
{
    [AttributeUsage(
        AttributeTargets.Class | AttributeTargets.Method,
        Inherited = true,
        AllowMultiple = true)]
    public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
    {
        // ...
    }
}

It's error handling scope is limited to action methods within the MVC framework. This means it won't be able to catch and process exceptions raised from outside the ASP.NET MVC handler (e.g. exceptions at an earlier stage in the life cycle or errors in other handlers). It will equally not catch an exception if the action method is not part of the call stack (e.g. routing errors).

Additionally the HandleErrorAttribute only handles 500 internal server errors. For instance this will not be caught by the attribute:

[HandleError]
public ActionResult Index()
{
    throw new HttpException(404, "Not found");
}

You can use the attribute to decorate a controller class or a particular action method. It supports custom error pages per exception type out of the box:

[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]]
In order to get the HandleErrorAttribute working you also need to turn customErrors mode on in your web.config:

<system.web>
    <customErrors mode="On" />
</system.web>

Use case

The HandleErrorAttribute is the most limited in scope. Many application errors will bypass this filter and therefore it is not ideal for global application error handling.

It is a great tool for action specific error handling like additional fault tolerance for a critical action method though.

Controller.OnException Method


The OnException method gets invoked if an action method from the controller throws an exception. Unlike the HandleErrorAttribute it will also catch 404 and other HTTP error codes and it doesn't require customErrors to be turned on.

It is implemented by overriding the OnException method in a controller:

protected override void OnException(ExceptionContext filterContext)
{
    filterContext.ExceptionHandled = true;
           
    // Redirect on error:
    filterContext.Result = RedirectToAction("Index", "Error");

    // OR set the result without redirection:
    filterContext.Result = new ViewResult
    {
        ViewName = "~/Views/Error/Index.cshtml"
    };
}

With the filterContext.ExceptionHandled property you can check if an exception has been handled at an earlier stage (e.g. the HandleErrorAttribute):

if (filterContext.ExceptionHandled)
    return;

Many solutions on the internet suggest to create a base controller class and implement the OnException method in one place to get a global error handler.

However, this is not ideal because the OnException method is almost as limited as the HandleErrorAttribute in its scope. You will end up duplicating your work in at least one other place.

Use case


The Controller.OnException method gives you a little bit more flexibility than the HandleErrorAttribute, but it is still tied to the MVC framework. It is useful when you need to distinguish your error handling between regular and AJAX requests on a controller level.

Application_Error event


The Application_Error method is far more generic than the previous two options. It is not limited to the MVC scope any longer and needs to be implemented in the Global.asax.cs file:

protected void Application_Error(Object sender, EventArgs e)
{
    var raisedException = Server.GetLastError();

    // Process exception
}

If you've noticed it doesn't come from an interface, an abstract class or an overriden method. It is purely convention based, similar like the Page_Load event in ASP.NET Web Forms applications.

Any unhandeled exception within ASP.NET will bubble up to this event. There is also no concept of routes anymore (because it is outside the MVC scope). If you want to redirect to a specific error page you have to know the exact URL or configure it to co-exist with "customErrors" or "httpErrors" in the web.config.

Use case


In terms of global error logging this is a great place to start with! It will capture all exceptions which haven't been handled at an earlier stage. But be careful, if you have set filterContext.ExceptionHandled = true in one of the previous methods then the exception will not bubble up to Application_Error.

However, for custom error pages it is still not perfect. This event will trigger for all ASP.NET errors, but what if someone navigates to a URL which isn't handled by ASP.NET? For example try navigating to http://{your-website}/a/b/c/d/e/f/g. The route is not mapped to ASP.NET and therefore the Application_Error event will not be raised.

customErrors in web.config


The "customErrors" setting in the web.config allows to define custom error pages, as well as a catch-all error page for specific HTTP error codes:

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error/Index">
        <error statusCode="404" redirect="~/Error/NotFound"/>
        <error statusCode="403" redirect="~/Error/BadRequest"/>
    </customErrors>
<system.web/>

By default "customErrors" will redirect a user to the defined error page with a HTTP 302 Redirect response. This is really bad practise because the browser will not receive the appropriate HTTP error code and redirect the user to the error page as if it was a legitimate page. The URL in the browser will change and the 302 HTTP code will be followed by a 200 OK, as if there was no error. This is not only confusing but has also other negative side effects like Google will start indexing those error pages.

You can change this behaviour by setting the redirectMode to "ResponseRewrite":

<customErrors mode="On" redirectMode="ResponseRewrite">

This fixes the initial problem, but will give a runtime error when redirecting to an error page now:

Runtime Error

An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.
This happens because "ResponseRewrite" mode uses Server.Transfer under the covers, which looks for a file on the file system. As a result you need to change the redirect path to a static file, for example to an .aspx or .html file:

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error.aspx"/>
Now there is only one issue remaining with this configuration. The HTTP response code for the error page is still "200 OK". The only way to fix this is to manually set the correct error code in the .aspx error page:

<% Response.StatusCode = 404; %>
This is already pretty good in terms of custom error pages, but we can do better!

Noticed how the customErrors section goes into the system.web section? This means we are still in the scope of ASP.NET.

Files and routes which are not handled by your ASP.NET application will render a default 404 page from IIS (e.g. try http://{your-website}/not/existing/image.gif).

Another downside of customErrors is that if you use a HttpStatusCodeResult instead of throwing an actual exception then it will bypass the ASP.NET customErrors mode and go straight to IIS again:

public ActionResult Index()
{
    return HttpNotFound();
    //throw new HttpException(404, "Not found");
}

In this case there is no hack which can be applied to display a friendly error page which comes from customErrors.

Use case


The customErrors setting was for a long time the best solution, but still had its limits. You can think of it as a legacy version of httpErrors, which has been only introduced with IIS 7.0.

The only time when customErrors still makes sense is if you can't use httpErrors, because you are running on IIS 6.0 or lower.

httpErrors in web.config

The httpErrors section is similar to customErrors, but with the main difference that it is an IIS level setting rather than an ASP.NET setting and therefore needs to go into the system.webserver section in the web.config:

<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <clear/>
      <error
        statusCode="404"
        path="/WebForms/Index.aspx"
        responseMode="ExecuteURL"/>
    </httpErrors>
<system.webServer/>

It allows more configuration than customErrors but has its own little caveats. I'll try to explain the most important settings in a nutshell:

httpErrors can be inherited from a higher level (e.g. set in the machine.config)
Use the <remove/> tag to remove an inherited setting for a specific error code.
Use the <clear/> tag to remove all inherited settings.
Use the <error/> tag to configure the behaviour for one error code.
responseMode "ExecuteURL" will render a dynamic page with status code 200.
The workaround to set the correct error code in the .aspx page works here as well.
responseMode "Redirect" will redirect with HTTP 302 to a URL.
responseMode "File" will preserve the original error code and output a static file.
.aspx files will get output in plain text.
.html files will render as expected.
The main advantage of httpErrors is that it is handled on an IIS level. It will literally pick up all error codes and redirect to a friendly error page. If you want to benefit from master pages I would recommend to go with the ExecuteURL approach and status code fix. If you want to have rock solid error pages which IIS can serve even when everything else burns, then I'd recommend to go with the static file approach (preferably .html files).

Use case


This is currently the best place to configure friendly error pages in one location and to catch them all. The only reason not to use httpErrors is if you are still running on an older version of IIS (< 7.0).

Custom HttpModule


Last but not least I would like to quickly touch on custom HttpModules in ASP.NET. A custom HttpModule is not very useful for friendly error pages, but it is a great location to put global error logging in one place.

With a HttpModule you can subscribe to the OnError event of the HttpApplication object and this event behaves same way as the Application_Error event from the Global.asax.cs file. However, if you have both implemented then the one from the HttpModule gets called first.

The benefit of the HttpModule is that it is reusable in other ASP.NET applications. Adding/Removing a HttpModule is as simple as adding or removing one line in your web.config:

<system.webServer>
    <modules>
        <add name="CustomModule" type="SampleApp.CustomModule, SampleApp"/>
    </modules>
</system.webSe
rver>

 

 


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 Add a Video in ASP.NET MVC 5?

clock April 15, 2016 21:45 by author Anthony

In this tutorial, you’re going to learn how to add video using Entity Framework. We will be building a form for adding a new video to the database.Step 1: Creating a Page to Add a Video

Before we get started, let’s take a closer look at routing.

Earlier I told you that the routing engine determines the name of the controller and the action from the URL of the request. The default rule (or the default convention) targets a URL with the pattern /controller/action/id. Here both action and id are optional. If action is not specified, Index is assumed as the action name.

For the purpose of this section, we need a new page for the user to add a new video. To do this, we’re going to create a new action that responds to a URL like /videos/new. Inside this action, we’ll return a view which will include a data entry form for adding a video.

First, go to VideosController and create a new action like this:
public ActionResult New()
{
    return View();
}

All we do here is simply return a view. Let’s create the corresponding view. In Solution Explorer, expand the Views folder, right-click the Videos folder, and go to Add > View…. Set the name of the view to New and make sure _Layout.cshtml is selected as the layout (similar to the last section).

image09

Next, set the model behind this view on the top:

@model Beaver.Models.Video

We set the model to the Video because we’re going to capture a Video object in this form.
@using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" }))
{

}



Here we are using Razor syntax (note the @) to write C# code. Html.BeginForm is a helper method, which we use to render an HTML form element. It returns an instance of MvcForm, which is a disposable object. By wrapping it inside a using block, we can ensure that it will be properly disposed.

The first and second arguments specify the name of the action and controller that will be called when we post this form. In this case, we expect an action named Add in our VideosController to be called. We haven’t created this action yet, but we’ll do so soon.

The third argument specifies the form method. In HTML forms, we have two methods: GET and POST. When sending data for modification to the server, we should always use the POST method.

The last argument is an anonymous object ( new {} ) that specifies any additional attributes to add to the HTML markup. So, when this code is executed, the view engine will render something like this:

<form action=”/videos/add” method=”post” class=”form”>
</form>

We use the form CSS class to give a nice, modern look to our forms. This CSS class is defined in Bootstrap, which is a CSS framework for building modern and responsive (mobile- and tablet-friendly) web applications. When you create an ASP.NET MVC project in Visual Studio, Bootstrap is automatically added for you.

We added the form. Now, we need to add three input fields in this form: Title, Description and Genre. Write this code inside the using block:Now, write the following code in the view to create an HTML form element:
 <div class="form-group">
        @Html.LabelFor(m => m.Title)
        @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

Here we have three sections, each wrapped with a div with a form-group class. Again, this is one of the classes that is defined in Bootstrap. If you follow Botostrap’s markup, you always get a nice, clean form that renders well both on the desktop and on mobile devices.

Inside each form-group, we have a label and an input field. Look at the first form-group.

<div class="form-group">
    @Html.LabelFor(m => m.Title)
    @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
</div>

We’re using Html.LabelFor to render a label for the Title property of the Video class.

@Html.LabelFor(m => m.Title)

The expression m => m.Title is a lambda expression that we use to access a property in the model of this view. If you’re not familiar with lambda expressions, check out my C# Advanced course on Udemy. When this line is executed by the view engine, we’ll get an HTML markup like this:

<label for=”Title”>Title</label>
Next, we use Html.TextBoxFor helper method to render a text box.

@Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
Again, we use a lambda expression to specify the target property. Also, note that the second argument to this method is an anonymous object that specifies any additional attributes to add to the markup, in this case form-control CSS class. This is another Bootstrap class that gives our text boxes a bit of padding, round corners and a nice effect when the input is in focus. The result will be HTML markup like this:

<input type=”text” id=”Title” name=”Title” class=”form-control”></input>
Now you read the second form-group.

<div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

It’s very similar to the first one, except that here we use the Html.TextAreaFor helper method to render a textarea input element instead of a text box. This allows the user to write a description that is more than one line.

And finally, in the third form-group, we use a different helper method (Html.EnumDropDownListFor) to render a drop-down list for the Genre property, which is an enum:

<div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

For the last step, we need a button to submit the form. Add this markup inside the using block, after all form groups:

<input type="submit" class="btn btn-primary" value="Save" />
Here, btn and btn-primary are both Bootstrap classes that make our buttons look cool and modern.

Your entire using block should look like this:

@using (Html.BeginForm("Add", "Videos", FormMethod.Post, new { @class = "form" }))
{
    <div class="form-group">
        @Html.LabelFor(m => m.Title)
        @Html.TextBoxFor(m => m.Title, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = 4 })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Genre)
        @Html.EnumDropDownListFor(m => m.Genre, new { @class = "form-control" })
    </div>

    <input type="submit" class="btn btn-primary" value="Save" />
}

Now it’s time to review what we have done. Run the application with Ctrl+F5 and look at the form we’ve built:

Note how the input fields and the button look. This is all because of the beautiful styles defined in Bootstrap.
In this step, we added a new action to our controller that returned a view. We created a view with a form to add a video.

 


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



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in