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

European ASP.NET MVC 4 Hosting - Amsterdam :: Create a Mobile Application in ASP.NET MVC 4

clock March 26, 2012 07:51 by author Scott

In this post, I will show you three new functionalities brought by MVC4 for mobile websites.

-          The mobile Application Template

-          The View Switcher

-          The Display mode by Browser type

Smartphone and tablet are able to read websites not optimized for tiny screen but if a user can jump automatically on an optimized version of the website, it’s better for everyone!

One interesting feature of this new version of the ASP.NET MVC framework 4 is the new
Mobile Application template. With this template you’ll be able to develop quickly a website especially for mobile and tablet.

1 – Create a full-mobile Website


In Visual Studio, Create a new MVC4 project and select the “Mobile Application” template.




I consider that you’ve already develop a classic MVC application. If true, you will not be surprised by the generated project. It’s almost the same as a classic MVC desktop website.


So what the difference?

In the “content” folder you will find another JavaScript library:
jQuery Mobile. ASP.NET MVC4 Mobile Template is based on the famous JavaScript framework for mobile application. You can learn a lot if you visit the jQuery mobile website.



Models and Controller are similar to a classic MVC Application.

In the view, you just have to add some tag to tell how jQuery mobile needs to display the page.

If we take a look at this code (Menu of the website generated by MVC4), you will probably recognize the Razor syntax. Nothing change when you want to develop Mobile Application with MVC4. You just have to use special attribute in your HTML.

Here, we declare a classic HTML list….and jQuery Mobile will transform it into an accessible list for mobile devices user.

<ul data-role="listview" data-inset="true">

<li data-role="list-divider">Navigation</li>

<li>@Html.ActionLink("About", "About", "Home")</li>

<li>@Html.ActionLink("Contact", "Contact", "Home")</li>

</ul>

 

 



European ASP.NET MVC 3 Hosting - Amsterdam :: How to Set up Custom Error Pages to Handle Errors in “non-AJAX” Requests and jQuery AJAX Requests

clock March 22, 2012 06:56 by author Scott

In this blog post I will show how to set up custom error pages in ASP.NET MVC 3 applications to create user-friendly error messages instead of the (yellow) IIS default error pages for both “normal” (non-AJAX) requests and jQuery AJAX requests.

In this showcase we will implement custom error pages to handle the HTTP error codes 404 (“Not Found”) and 500 (“Internal server error”) which I think are the most common errors that could occur in web applications. In a first step we will set up the custom error pages to handle errors occurring in “normal” non-AJAX requests and in a second step we add a little JavaScript jQuery code that handles jQuery AJAX errors.


We start with a new (empty) ASP.NET MVC 3 project and activate custom errors in the Web.config by adding the following lines under <system.web>:


<customErrors
mode="On" defaultRedirect="/Error">
  <error redirect="/Error/NotFound" statusCode="404"/>
  <error redirect="/Error/InternalServerError" statusCode="500"/>
</customErrors>


Note: You can set
mode=”Off” to disable custom errors which could be helpful while developing or debugging. Setting mode=”RemoteOnly” activates custom errors only for remote clients, i.e. disables custom errors when accessing via http://localhost/[...]. In this example setting mode=”On” is fine since we want to test our custom errors. You can find more information about the <customErrors> element here.

In a next step we
remove the following line in Global.asax.cs file:

filters.Add(new HandleErrorAttribute());


and add a new
ErrorController (Controllers/ErrorController.cs):

public
class ErrorController : Controller
{

  public ActionResult Index()
  {
    return InternalServerError();
  }

  public ActionResult NotFound()
  {
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = (int)HttpStatusCode.NotFound;
    return View("NotFound");
  }

  public ActionResult InternalServerError()
  {
    Response.TrySkipIisCustomErrors = true;
    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    return View("InternalServerError");
  }
}


In a last step we add the
ErrorController‘s views (Views/Error/NotFound.cshtml and Views/Error/InternalServerError.cshtml) that defines the (error) pages the end user will see in case of an error. The views include a partial view defined in Views/Shared/Error/NotFoundInfo.cshtml respectively Views/Shared/Error/InternalServerErrorInfo.cshtml that contains the concrete error messages. As we will see below using these partial views enables us to reuse the same error messages to handle AJAX errors.

Views/Error/NotFound.cshtml:


@{

  ViewBag.Title = "Not found";
}

@{

  Html.RenderPartial("Error/NotFoundInfo");
}


Views/Shared/Error/NotFoundInfo.cshtml:

The URL you have requested was not found.


Views/Error/InternalServerError.cshtml:

@{
  ViewBag.Title = "Internal server error";
}
@{
  Html.RenderPartial("Error/InternalServerErrorInfo");
}

Views/Shared/Error/InternalServerErrorInfo.cshtml:

An internal Server error occured.

To handle errors occurring in (jQuery) AJAX calls we will use jQuery UI to show a dialog containing the error messages. In order to include jQuery UI we need to add two lines to Views/Shared/_Layout.cshtml:

<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />

<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>

Moreover we add the following jQuery JavaScript code (defining the global AJAX error handling) and the Razor snippet (defining the dialog containers) to Views/Shared/_Layout.cshtml:

<
script type="text/javascript">
  $(function () {
    // Initialize dialogs ...
    var dialogOptions = {
      autoOpen: false,
      draggable: false,
      modal: true,
      resizable: false,
      title: "Error",
      closeOnEscape: false,
      open: function () { $(".ui-dialog-titlebar-close").hide(); }, // Hide close button
      buttons: [{
        text: "Close",
        click: function () { $(this).dialog("close"); }
      }]
    };
    $("#InternalServerErrorDialog").dialog(dialogOptions);
    $("#NotFoundInfoDialog").dialog(dialogOptions);

    // Set up AJAX error handling ...
    $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError)
{

      if (jqXHR.status == 404) {
        $("#NotFoundInfoDialog").dialog("open");
      } else if (jqXHR.status == 500) {
        $("#InternalServerErrorDialog").dialog("open");
      } else {
        alert("Something unexpected happend :( ...");
      }
    });
  });
</
script>

<div id="NotFoundInfoDialog">
  @{ Html.RenderPartial("Error/NotFoundInfo"); }
</div>
<div id="InternalServerErrorDialog">
  @{ Html.RenderPartial("Error/InternalServerErrorInfo"); }
</div>

As you can see in the Razor snippet above we reuse the error texts defined in the partial views saved in Views/Shared/Error/.


To test our custom errors we define the HomeController (Controllers/HomeController.cs) as follows:

  public class HomeController : Controller
  {
  public ActionResult Index()
  {
    return View();
  }
  public ActionResult Error500()
  {
    throw new Exception();
  }
}

and the corresponding view Views/Home/Index.cshtml:

@{
  ViewBag.Title = "ViewPage1";
}

<script type="text/javascript">
  $function () {
    $("a.ajax").click(function (event) {
      event.preventDefault();
      $.ajax({
      url: $(this).attr('href'),
    });
  });
});
</script>

<ul>
  <li>@Html.ActionLink("Error 404 (Not Found)", "Error404")</li>
  <li>@Html.ActionLink("Error 404 (Not Found) [AJAX]", "Error404", new { },
new { Class = "ajax" })</li>

  <li>@Html.ActionLink("Error 500 (Internal Server Error)", "Error500")</li>
  <li>@Html.ActionLink("Error 500 (Internal Server Error) [AJAX]", "Error500", new { }, new { Class = "ajax" })</li>
</ul>

To test the custom errors you can launch the project and click one of the four links defined in the view above. The “AJAX links” should open a dialog containing the error message and the “non-AJAX” links should redirect to a new page showing the same error message.

Summarized this blog post shows how to set up custom errors that handle errors occurring in both AJAX requests and “non-AJAX” requests. Depending on the project, one could customize the example code shown above to handle other HTTP errors as well or to show more customized error messages or dialogs.

 



European ASP.NET MVC 3 Hosting :: Areas in ASP.NET MVC3

clock March 15, 2012 08:11 by author Scott

Description

Normally in a MVC3 application we have generally 3 sections.


Model, Controller, View.


Now in a real-world project in our Application there may be many modules.


So separating each of the modules in our MVC3 application is highly recommendable.


In ASP.Net MVC3 we have features called "area" where we can separate into different modules.


For e.g. ADMIN, CUSTOMER, PRODUCT etc.


Now I will show you an example of how to create the "AREA" in MVC3.


Step 1:

Now first create an ASP.Net MVC3 application.


Step 2:

Now right-click the project and "add" a new area with the name "Admin"; that means in our project there are an "admin" module. See the following picture:


Step 3:

After adding the "admin" area you will see that a separate "Areas" folder will be created. Under this folder controller, model and views, shared folders will be generated.


Now under the "Controller" folder add a new controller named "admin controller".


Now from the "admincontroller" create a new view named "index" from the "index" method.


After that copy the "_layout.cshtml" from the main project and paste it under the "Areas" Shared folder.


Now the whole structure will look like the following once.




Step 4:


Now add a new action link for "Admin" under the _layout.cshtml" like the following picture:




<li>@Html.ActionLink("Admin", "Index", "Admin")</li>

So the admin link will be created and when we click the "admin" link it will redirect to the "admin" part of our project which is under the "Areas".

Step 5:


Now go to the "AdminAreaRegistration" file (just the following picture) and modify the existing code like below:




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

I have added here only Controller Name "Admin"( controller = "Admin") extra under the new {} section.


Now run the application it will look like the following picture:




See here "Admin" link has come.


Now after clicking the admin link it will show like the following picture:




See the url routing. It calls our "Admin " Areas part.


So by this way we can group our project modules into our ASP.Net MVC3 application.


Conclusion


So in this article we have learned what is the purpose of use of "Area" features in ASP.Net MVC3 and how to implement them.



European ASP.NET MVC 3 Hosting :: Areas in ASP.NET MVC3

clock March 15, 2012 08:11 by author Scott

Description

Normally in a MVC3 application we have generally 3 sections.


Model, Controller, View.


Now in a real-world project in our Application there may be many modules.


So separating each of the modules in our MVC3 application is highly recommendable.


In ASP.Net MVC3 we have features called "area" where we can separate into different modules.


For e.g. ADMIN, CUSTOMER, PRODUCT etc.


Now I will show you an example of how to create the "AREA" in MVC3.


Step 1:

Now first create an ASP.Net MVC3 application.


Step 2:

Now right-click the project and "add" a new area with the name "Admin"; that means in our project there are an "admin" module. See the following picture:


Step 3:

After adding the "admin" area you will see that a separate "Areas" folder will be created. Under this folder controller, model and views, shared folders will be generated.


Now under the "Controller" folder add a new controller named "admin controller".


Now from the "admincontroller" create a new view named "index" from the "index" method.


After that copy the "_layout.cshtml" from the main project and paste it under the "Areas" Shared folder.


Now the whole structure will look like the following once.




Step 4:


Now add a new action link for "Admin" under the _layout.cshtml" like the following picture:




<li>@Html.ActionLink("Admin", "Index", "Admin")</li>

So the admin link will be created and when we click the "admin" link it will redirect to the "admin" part of our project which is under the "Areas".

Step 5:


Now go to the "AdminAreaRegistration" file (just the following picture) and modify the existing code like below:




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

I have added here only Controller Name "Admin"( controller = "Admin") extra under the new {} section.


Now run the application it will look like the following picture:




See here "Admin" link has come.


Now after clicking the admin link it will show like the following picture:




See the url routing. It calls our "Admin " Areas part.


So by this way we can group our project modules into our ASP.Net MVC3 application.


Conclusion


So in this article we have learned what is the purpose of use of "Area" features in ASP.Net MVC3 and how to implement them.



European ASP.NET MVC 3 Hosting :: Custom Error Pages and Error Handling in ASP.NET MVC 3

clock March 9, 2012 07:32 by author Scott

In ASP.NET MVC 3 a new bit of code appeared in the global.asax.cs file:

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


The above method is called from the
Application_Start() method.

Out of the box, what this does is set up a global filter for handling errors. You can still attribute controller methods or classes as before, but now, if you don’t have a specific
HandleErrorAttribute attached to the controller method or class then the global one will take over and be processed.

However, you are not going to get custom errors just yet. If you have a bit of code that causes an exception to be thrown that is not caught then you will just end up with the Yellow Screen of Death as before. For example, this code:


public class HomeController : Controller
{
    // ...

    public ActionResult About()
    {
        throw new Exception("This is not good. Something bad happened.");
    }
}


Will produce this error




The missing part of the puzzle is to turn on Custom Errors. This happens in the web.config file. There are three basic options for the mode: “Off” which will show the YSOD to everyone, “RemoteOnly” which shows the YSOD on the local machine (the web server) and the custom error to everyone else, and “On” which shows the custom error to everyone including the local machine.


For development purposes I tend to leave it set to “RemoteOnly” so that I get the YSOD and I get to see what the error is, yet everyone else gets the custom error. However, for developing the actual custom errors themselves we’ll need to set the mode to “On” so we, as developers, get to see the error.


<system.web>
  <customErrors mode="On" defaultRedirect=”~/BadError.htm"/>
</system.web>

The defaultRedirect does not go to a controller action, it is set to a static HTML page that will be displayed if all else goes wrong. This is a final backstop to ensure that the user at least will see something nice event if the error page itself has some issues.


Normally, the error will show the ~/Views/Shared/Error.cshtml view. However, since the view can throw an exception itself there ought to be a backstop custom error page.

The HandleErrorAttribute defaults to using the view "Error" which will display shared view ~/Views/Shared/Error.cshtml.

You can change that by setting the view property on the HandleErrorAttrubute, like this:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute {View = "MyCustomError"});
}

I’ve set my error view to display the details of the exception for the purposes of this demo.

@model System.Web.Mvc.HandleErrorInfo

@{
    ViewBag.Title = "Error";
}

<h2>
    Sorry, an error occurred while processing your request.
</h2>
<p>Controller = @Model.ControllerName</p>
<p>Action = @Model.ActionName</p>
<p>Message = @Model.Exception.Message</p>
<p>StackTrace :</p>
<pre>@Model.Exception.StackTrace</pre>

NOTE: In normal production code you would never expose the details of the exception like this. It represents a considerable security risk and a potential attacker could use the information to gain valuable information about your system in order to construct an attack against it.

Now, if we re-run the same application and go to the About page (handled by the HomeController’s About action) then we will get our custom error page.

Performing additional actions on an exception

Overriding OnException in a Controller


If you want to perform additional actions, rather than just simply show a custom error page, then you can override the OnException method from the Controller class on your own controller derived class. If you want to do this for all controllers then you may want to create a common base controller that all your controllers inherit from. For example:

public class CommonController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        // Do additional things like logging here.
        base.OnException(filterContext);
    }
}

Then in each of your controllers, inherit from this common controller like this:

public class HomeController : CommonController
{ ...

That will ensure that all your controller have the same functionality.

Creating a FilterAttribute


You could alternatively create a FilterAttribute. This can provide benefits of providing global functionality if you add it to the global filter collection, or very fine grained functionality if you need it on a few sparse controller actions by adding it as an attribute on the controller action.

The filter may look like this:

public class LogExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        // Log the exception here with your logging framework of choice.
    }
}

If you want to have the filter applied to all controller actions, you can set it up in the RegisterGlobalFilters method in the Global.asax.cs file like this:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new LogExceptionFilterAttribute());
    filters.Add(new HandleErrorAttribute());
}

Or, if you prefer to have finer grained control you can decorate individual controller classes or controller actions with it, like this:

[LogExceptionFilter()]
public ActionResult About()
{
    throw new Exception("This is not good. Something bad happened.");
}

 



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 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 5 Hosting, and SQL 2014 Hosting.


Tag cloud

Sign in