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 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.");
}

 



European ASP.NET MVC 3 Hosting - Amsterdam :: Set up custom error pages to handle errors in “non-AJAX” requests and jQuery AJAX requests in ASP.NET MVC 3

clock February 14, 2012 07:03 by author Scott

In this blog post I will show how to set up custom error pages in ASP.NET MVC 3 applications to show 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.

When thinking about error handling in ASP.NET MVC 3 applications you should take a look at
ELMAH (Error Logging Modules and Handlers for ASP.NET), a tool that logs/handles errors on server side and which works perfectly in combination with the approach shown above.



Europe ASP.NET MVC 3 Hosting - Amsterdam :: How to return 404 Http status code from ASP.NET MVC Application?

clock February 7, 2012 07:49 by author Scott

ASP.NET MVC3 includes a new class HttpNotFoundResult in  System.Web.Mvc namespace.

HttpNotFoundResult: Instance of HttpNotFoundResult class indicates to client(browser) that the requested resource was not found. It returns a 404 HTTP status code to the client. Generally we return 404 status code if a requested webpage is not available. In case of MVC applications we return 404 status code is in terms of resources, for example we are searching for particular user profile in the portal, if the user profile is not found, we can return 404.

How to return 404 status code from a MVC application?

First way is to instantiate HttpNotFoundResult class and return the object.

public ActionResult Index()
{
var result = new HttpNotFoundResult();
return result;
}

Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.


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

we can return 404 along with custom status code description,using the overloded version of HttpNotFound(string statusDescription).

public ActionResult Index()
{
return HttpNotFound("can not find requested resource");
}



European ASP.NET MVC 3 Hosting :: Creating a Simple Sign-Up Form in ASP.NET MVC 3

clock January 31, 2012 06:48 by author Scott

In this article I'm going to demonstrate how to create a simple sign-up form using ASP.NET MVC 3. So basically in this demo you will learn the following:

How to insert data to the database with Entity Framework
How to validate the Form using Data Annotations
How to Authenticate users after sign up using FormsAuthentication

STEP 1. Adding a new ASP.NET MVC project

Let's go ahead and fire up Visual Studio 2010 and then select File -> New Project -> ASP.NET MVC 3 Web Application. See the screen shot below for more clearer view:




Now click OK and on the next form select Empty Template -> select Razor as the View engine and then click OK to generate the default files.

STEP 2: Setting up the Model

In this demo, I'm going to use Entity framework as our Data Access mechanism sothat we can program against the conceptual application model instead of progamming directly against  our database.

Add the following folders under the Models folder:

    DB
    ObjectManager
    ViewModel

The application structure would like something like below:



We will create our Entity Model (EDMX) in the DB folder. To do this right click on the "DB" folder and select Add -> New Item -> Data -> ADO.NET Entity Data Model.



Noticed that I named the entity as "SampleModel" just for the purpose of this demo. You may want to name it to a more appropriate name based on your requirements but for this example let's just use "SampleModel". Now click Add to continue and on the next step select "Generate from database" and click Next. On the next step you can connect or browse to the database that you want to use in the application and test the connection string by clicking on the "Test Connection" button and if it succeeds then you can continue by clicking OK and then Next.

Note that in this example I created a simple database called "DeveloperReport.mdf" and added it into the application's App_Data folder and use it as our database. See the screen shot below:



On the next step we can add the table(s), views or stored procedures that we want to use in the application by selecting the checkbox. See below screenshot:



Noticed that I've only selected the "SysUser" table. This is because we are going to use this table for doing insert and we don't need anything else. Now click on Finish button to generate the entity model for you. See the screenshot below:



What happend there is that EF will automatically generates the Business object for you within the Entity Data Model(EDM) that we have just created and let you query against it.The EDM is the main gateway by which you retrieve objects from the database and resubmit changes.

STEP 3: Adding the ViewModel Class

Just to recap Entity Framework will generate the business objects and manage Data Access within the application. As a result, the class SysUser is automatically created by EF and it features all the fields in the database table as properties of the class.

I don't want to use this class direclty in the View so I decided to create a separate class that just holds the properties I need in the View. Now let's add a the UserView class by right-clicking on the "ViewModels" folder then select Add -> Class. Here's the code block for the "UserView.cs" class.

using System.ComponentModel.DataAnnotations;

namespace MVCDemo.Models.ViewModels {
    public class UserView {
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "Contact Number")]
        public string ContactNumber { get; set; }

        [Required]
        [Display(Name = "Login ID")]
        public string LoginID { get; set; }

        [Required]
        [Display(Name = "Password")]
        public string Password { get; set; }
    }
}

Noticed that I added the Required and DisplayName attributes for each property in the UserView class. This attributes is called Data Annotations. Data annotations are attribute classes that live in the System.ComponentModel.DataAnnotations namespace that you can use to to decorate classes or properties to enforce pre-defined validation rules.

I'll use this validation technique because I want to keep a clear separation of concerns by using the MVC pattern and couple that with data annotations in the model, then your validation code becomes much simpler to write, maintain, and test.

For more information about Data Annotations then you can refer this link: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx. And of course you can find more examples about it by doing a simple search at google /bing.

STEP 4: Adding the UserManager Class

The next step that we are going to do is to create the User manager class that would handle the (CRUD operations) create,update,fetch and delete operations of a certain table. The purpose of this class is to separate the actual data opertions from our controller and to have a central class for handling insert,update,fetch and delete operations. But please note that in this example I'm only be doing the insert part in which a user can add new data from the View to the database. I'll talk about how to do update,fetch and delete with MVC in my next article. So this time we'll just focus on the insertion part first.

Now right click on the "Model" folder and add a new class by selecting Add -> Class and since we are going to manipulate the SysUser table then we will name the class as "UserManager". Here's the code block for the "UserManager.cs" class:

using MVCDemo.Models.DB;
using MVCDemo.Models.ViewModels;

namespace MVCDemo.Models.ObjectManager {
    public class UserManager {

        private DeveloperReportEntities dre = new DeveloperReportEntities();

        public void Add(UserView user) {
            DB.SysUser sysUser = new DB.SysUser();
            sysUser.SysUserLoginID = user.LoginID;
            sysUser.SysPassword = user.Password;
            sysUser.FirstName = user.FirstName;
            sysUser.LastName = user.LastName;
            sysUser.ContactNumber = user.LastName;

            dre.AddToSysUsers(sysUser);
            dre.SaveChanges();
        }

        public bool IsUserLoginIDExist(string userLogIn) {
            return (from o in dre.SysUsers where o.SysUserLoginID == userLogIn select o).Any();
        }
    }
}

STEP 4: Adding the Controllers

Since our model is already set then let's go ahead and add the "AccountController". To do this just right click on the "Controllers" folder and select Add -> Controller. Since our aim is to create a simple sign-up form then name the controller as "AccountController" and then click Add to generate the "AccountController" class for you.

Now here's the code block for the "AccountController":

using System.Web.Mvc;
using System.Web.Security;
using MVCDemo.Models.ViewModels;
using MVCDemo.Models.ObjectManager;

namespace MVCDemo.Controllers
{
    public class AccountController : Controller
    {
        // GET: /Account/SignUp
        public ActionResult SignUp() {
            return View("SignUp");
        }

        // POST: /Account/SignUp
        [HttpPost]
        public ActionResult SignUp(UserView user) {
            try {
                if (ModelState.IsValid) {
                    UserManager userManager = new UserManager();
                    if (!userManager.IsUserLoginIDExist(user.LoginID)) {
                        userManager.Add(user);
                        FormsAuthentication.SetAuthCookie(user.FirstName, false);
                        return RedirectToAction("Welcome", "Home");
                    }
                    else {
                        ModelState.AddModelError("", "LogID already taken");
                    }
                }
            }
            catch {
                return View(user);
            }

            return View(user);
        }
    }
}

The AccountController has two main methods. The first one is the "SignUp" which returns the "SignUp.cshtml" View. The second one also named as "SignUp" but it is decorated with the "[HttpPost]" attribute. This attribute specifies that the overload of the "SignUp" method can be invoked only for POST requests.

The second method is responsible for inserting new entry to the database and automatically authenticate the users using FormsAuthentication.SetAuthCookie() method. this method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication. After authenticating, we then redirect the users to the Welcome.cshtml page.

Now add another Controller and name it as "HomeController". This controller would be our controller for our default page. We will create the "Index" and the "Welcome" View for this controller in the next step. Here's the code for the "HomeController" class:


using System.Web.Mvc;

namespace MVCDemo.Controllers
{
    public class HomeController : Controller
    {
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult Welcome() {
            return View();
        }

    }
}

Noticed that we have two ActionResult method in the "HomeController". The "Index" method serve as our default redirect page and the "Welcome" method will be the page where we redirect the users after they have successfully registered. We also decorated it with the "[Authorize]" attribute so that this method will only be available for the logged-in users.

STEP 5: Adding the Views

First let's add the following folders below under the "Views" folder:

    Home
    Account

Note: The reason for this is that the folder name should match the name of the Controllers you've created. So if you have HomeController then you should have a "Home" folder within your View.

Now under the "Home" folder add a new View. To do this just right click on the "Home" folder and select Add -> View. Name the view as "Index" and click Add to generate the Web Page (.cshtml). Here's the mark-up of the Index.cshtml:

@{
    ViewBag.Title = "Welcome";
}

<h2>Welcome</h2>

@Html.ActionLink("Click here to sign-up", "SignUp", "Account")

As you can see there's no fancy about the mark-up above except that it contains the ActionLink which redirect you to the "SignUp" view within the "Account" folder. Now add again another View under the "Home" folder and name the view as "Welcome". The reason why we add the Welcome.cshtml view is because we will redirect the user in this page after they successfully signed up and nothing more. Here's the mark-up of the Welcome.cshtml:

@{
    ViewBag.Title = "Welcome";
}

<h2>
Hi <b>@Context.User.Identity.Name</b>! Welcome to my website!</h2>

Now under the "Account" folder add a new view and name it as "SignUp" and check the checkbox that says "create a strongly-typed views and in the Model class dropdownlist select "UserView" and then in the Scaffold template select "Create" and finally click Add to generate the Web Page for you. Take a look at the screen shot below for more clearer view of what I am talking about:



And here's the generated mark up of the SignUp.cshtml:

@{
    ViewBag.Title = "SignUp";
}

<h2>Sign-Up</h2>

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

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>UserView</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ContactNumber)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ContactNumber)
            @Html.ValidationMessageFor(model => model.ContactNumber)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LoginID)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LoginID)
            @Html.ValidationMessageFor(model => model.LoginID)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Return to Home page","Index", "Home")
</div
>

The mark-up above is a strongly-type view. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor. By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. In this case it uses the MVCDemo.Models.ViewModels.UserView.

The View structure would like something like below:

Then, run the application and fill your details. Hope it helps.



European ASP.NET MVC 3 Hosting :: WebGrid in ASP.Net MVC3 Razor with Entity Framework

clock January 12, 2012 07:24 by author Scott

Step 1:

Create a new ASP.Net MVC 3 application with an empty web application. While creating the project check the radio button "UnitTest".

Step 2:

Now under the "Model" folder create two classes.

1.       Blog

2.       Comments

Step 3:

Now In the Blog Class Copy the following code:

public
class Blog
    {
       
        [Key]      
        public int BlogId { get; set; }

        [Required(ErrorMessage = "BlogName is required")]
        public string BlogName { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [StringLength(120, ErrorMessage = "Description Name Not exceed more than 120 words")]
        public string Description { get; set; }
        public string Body { get; set; }

        public virtual  List<Comments > Comments_List { get; set; }

    }

See here is the validation of each property. And also hold the list of comments. That means 1 blog contains many posts. So that is a one to many relationship.

The "Virtual" keywords means it will make the relationship.

Step 4:

Now in the Comments class write the following code:

public
class Comments
    {
        [Key ]
        public int CommentId { get; set; }
          public string Comment { get; set; }
       
//[ForeignKey]
          public int BlogId { get; set; }
          public virtual Blog Blog { get; set; }
 
    }


See here we also have the object reference of the "blog" class. Before that I have used the virtual key word.

Step 5:

Now it's time to make the entity class by which the database and the table will create.

Create a "DatabaseContext" folder under the project. After that create a class named "BlogDbContext.cs" under the folder. This class is an entity class.

Step 6:

Now make a reference for the Entity Framework by clicking "Add Reference" under the project.



In my project I had already provided the dll. Without this dll the table cannot be created in the database by object class mapping.

Now paste the following code into the "BlogDbContext" class:

using
System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using blogmvc3.Models;

namespace blogmvc3.DatabaseContext
{
    public class BlogDbContext:
DbContext
    {
        public DbSet<Blog> Blog { get; set; }
        public DbSet<Comments> Comments { get; set; }
    }
}


See here in the Dbset we are passing a blog class and a comments class. The Dbset will create a table automatically with a relation in the database.

The Namespace "System.Data.Entity" is very important for that.

Step 7:

Now we have to configure the "web.config" file for the connection string. The web.config file is under the Main Solution Project. Not the Project web.config file.




Now paste the following connection string into the web.config file.

Step 8:

Now create a Controller Class named "HomeController" under the "ControllerFolder. After that check the "Add action for create.update,delete.." so it will automatically create the action mrthod in the Controller class.





Step 9:

Now in the "HomeController" Class first create an object of the "BlogDbContext" Class .

BlogDbContext
_db = new BlogDbContext();

After that in the Index Method write the following code:

public
ActionResult Index()
        {
            return View(_db.Comments .ToList ());
        }

Step 10:

Now create a master page in the Razor engine under the "shared" folder. Give it the name "_LayoutPage1.cshtml".

After that paste the following code there:

<!DOCTYPE html>

<html
>
<
head
>
    <title>@ViewBag.Title</title
>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"
/>
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script
>
   @*
<script src="../../Scripts/jquery-ui-1.8.11.custom.min.js" type="text/javascript"></script>
    <link href="../../Content/jquery-ui-1.8.11.custom.css" rel="stylesheet" type="text/css" />
*@
</head>

<body
>
    <div class="page">

        <div id
="header">
            <div id
="title">
                <h1>Blog Post</h1
>
            </div>

            <div id
="logindisplay">
                @*@Html.Partial("_LogOnPartial")
*@
            </div>

            <div id="menucontainer">

                <ul id
="menu">
                   @* <li>@html.actionlink("home", "index", "home")</li>
*@
                    @*<li>@Html.ActionLink("About", "About", "Home")</li>
*@
                   <li>@Html.ActionLink("home", "index", "home")</li
>
                     <li>@Html.ActionLink("Article Post", "CreateLogin", "Article")</li>
                     @*<li>@Html.ActionLink("BookCab", "CreateLogin", "Cab")</li>
*@
                </ul>

            </div
>
             <script type="text/javascript"><!--                 mce: 0--></script>

        </div>

        <div id
="main">
            @RenderBody()
            <div id
="footer">
            </div
>
        </div
>
    </div
>
</
body
>
</
html>


Step 11:

Now go the "Home controller". Right-click the Index Method and add a view. It will look like:



Please check "Create Strongly-typed Views".

Choose Model Class "Comments" Under DropDown List.

Select "Scaffold Template" List. After that press the "Add" button. It will automatically create a view named "Index" under the "Home" folder.

Step 12:

See the Index View Engine will create code for the list view automatically.

Now delete all the code and replace it with the following code:

@model IEnumerable
<blogmvc3.Models.Comments>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";

}
@{
    var grid = new WebGrid(source: Model, canPage: true, defaultSort: "BlogName", rowsPerPage: 3, canSort: true); 
    }

<h2>Web grid</h2
>
if (@Model != null ) 

 {    

  @grid.GetHtml(tableStyle:"grid",headerStyle: "head",  alternatingRowStyle: "alt",caption:
"WebGrid"
           )
 
 }

<p>

    @Html.ActionLink("Create New", "Create")
</p>


Now see this code section what is written above.



See first we are creating the WebGrid and after that in the constructor parameter we are passing a different property argument such as paging property, sorting, and rows per page.

And in the second we are are calling the WebGrid by calling the "@Html.WebGrid" property. Here also we are passing a parameter for the WebGrid.

Now run the application; it will look like the following figure:

See here the BlogId and Comments are displaying in the WebGrid (marked with red). And the paging facility is also done (marked with black).



European ASP.NET MVC 3 Hosting :: Allow User to Input HTML in ASP.NET MVC

clock January 4, 2012 11:27 by author Scott

I want to wish Happy New Year 2012 for all of you….

Sometimes when we submit HTML or JavaScript as input in ASP.NET MVC application we get an exception like "A potentially dangerous Request.Form value was detected from the client (……)”. Because ASP.NET MVC has built-in request validation that helps you automatically protect against cross-site scripting (XSS) attacks and HTML injection attacks, it will prevent the user from posting HTML or JavaScript as input.

But sometime we want to explicitly disable request validation. We want to allow user to post html as input like, for example we have view which take the blog post as input from rich text editor, In ASP.NET MVC we have multiple options to disable request validation at various levels.

In ASP.NET MVC (V1, V2, V3) we can use [ValidateInput(false)] attribute, to disable request validation during model binding. We should add this attribute on top the action method in controller to which you are submitting input.



[ValidateInput(false)] attribute disables request validation on complete model or view model, but we want to allow html on only few properties of model or view model, for example in BlogPost model class contains three properties Title, PostContent, List<Tag> .

Among three properties we want to allow html only for PostContent ,In ASP.NET MVC 3 we have granular control over request validation, ASP.NET MVC3 has built-in attribute to disable validation at property level. We can [AllowHtml] attribute on properties in model or view model to disable request validation.



[AllowHtml] attribute allows a request to include HTML markup during model binding by skipping request validation for the property.



European ASP.NET MVC Hosting :: ASP.NET MVC Error Handling using the HandleError Filter

clock December 23, 2011 05:37 by author Scott

ASP.NET Errors can be effectively handled using the HandleError filter, which specifies how exceptions which are thrown in a controller method are to be dealt with (note that ASP.NET MVC supports method filters, which allow for annotating controller methods to change their behavior).
Prior to using the HandleError filter, you will need to enable custom error handling for your ASP.NET MVC app in the web.config file by adding the below line in the system.web section:

<customErrors mode="On" />

The below code snippet show the HandleError filter being applied to the controller class. Thus, any exception which is thrown by an action method in the controller will be handled using the custom error policy.


namespace MVCApplicationDemo.Controllers {
[HandleError]
public class ProductController : Controller {

When the HandleError filter is applied without arguments, any exception thrown by the methods covered by the filter will result in the Views/Shared/Error.aspx view being used which just shows the message “Sorry, an error occurred while processing your request.” To test
this process, attempt to view details of a product which does not yet exist, such as with a URL as below:


http://localhost:51823/Product/Details/999990

The error message can be more specific and you may wish to give the user more detailed info. To do this create a view in the Views/Shared folder named NoRecordErr.aspx with the below content:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>
<asp:Content ID="errTitle" ContentPlaceHolderID="TitleContent" runat="server">
Error Occurred
</asp:Content>
<asp:Content ID="errContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>

Sorry, but that record does not yet exist.

</h2>
</asp:Content>

This is a modification of the default error view with a message to show the user that the product request does not yet exist in the database. Next, we can apply the HandleError filter to the Details controller method as in the below snippet:

[HandleError(View="NoRecordErr")]
public ActionResult Details(int id) {

The filter informs the MVC framework that it should use the NoRecordErr view for an exception that is thrown by the Details method. Now, you need to modify the backstop filter to be as show below:

[HandleError(Order=2)]
public class ProductController : Controller {

An Order value of 2 ensures the controller-wide filter is to be applied only in the event that there is not a HandleError filter with a higher order available. If you do not set a value for Order, the default error view takes precedence.
Now if a user attempts to requests details for a product which does not exist they will be served the new error view. The default error view will be served if other controller methods throw exceptions.


However as it currently stands a user will be informed that they requested a non-existent record for any exception arising from the Details method. Thus you will need to be even more specific.
First, create an exception in the ProductController class which will be used when a record the user has requested is not available:


class NoRecordErr : Exception {
}

The next step is to modify the Details method so that it explicitly checks whether the LINQ query returned a record and if not record was returned throw a new exception.

[HandleError(View="NoRecordErr",
ExceptionType=typeof(NoRecordErr))]
public ActionResult Details(int id) {
NorthwindEntities db = new NorthwindEntities();
var data = db.Products.Where(e => e.ProductID == id).Select(e => e);
if (data.Count() == 0) {
throw new NoRecordErr();
} else {
Product record = data.Single();
return View(record);
}
}

In summery we changed the HandleError filter by including a value for the ExceptionType property, then specifying the type of the exception the filter should to apply to. Now when a NoRecordErr() exception is thrown, the NoRecordErr.aspx view will instead be used. Alternatively, the generic Error.aspx will be used for other exception types (since we applied the controller-wide backstop filter).



European ASP.NET MVC 3 Hosting :: How to Create Radio Button in Asp.net mvc3 Razor Application

clock December 16, 2011 10:41 by author Scott

Here I will demonstrate how to use a Radio Button in an ASP.Net Mvc3 Razor File. Just assume, we have a Razor file named Employee details. Where you have to fill in the required employee details. Now in this form we have a "Gender" field name.

You have already created your Model Classes and Controller Classes. So in the Razor file how you will create the Radio Button.

We already know that @Html.Editorfor is for taking input data i.e. Textbox and @Html.Label is for displaying the label control.

Now you have to type @Html.RadibuttonFor just like image below and give the necessary parameters like the code given below.



@
Html.RadioButtonFor(model =>model.Gender,"Male",true) Male 
@Html.RadioButtonFor(model =>model.Gender,"Female",false) Female


Here the Radiobutton takes 3 parameters.

1. The attribute of your Model Class. For mine it is gender.

2. The passing value when you click the particular RadioButton. For my case when you click the 1st RadioButton and click the Submit Button. In the database it will save "Male".

3. By default which RadioButton will be selected? For mine in the case that the first RadioButton name "Male" will be selected.

Here I am giving the complete code for the Razor File. I hope You will get some information from here.

@model
CabAutomationSystem.Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2
>
<
scriptsrc="@Url.Content("~/Scripts/jquery.validate.min.js")"type="text/javascript"></script
>
<
scriptsrc="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"></script
>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset
>
<
legend>Employee</legend>

<divclass="editor-label">
@
Html.LabelFor(model =>model.EmployeeName)
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.EmployeeName)
@Html.ValidationMessageFor(model =>model.EmployeeName)
</div>

<divclass
="editor-label">
@Html.LabelFor(model =>model.EmployeeID)
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.EmployeeID)
@Html.ValidationMessageFor(model =>model.EmployeeID)
</div>

<divclass
="editor-label">
@Html.LabelFor(model =>model.ProjectName)
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.ProjectName)
@Html.ValidationMessageFor(model =>model.ProjectName)
</div>

<divclass
="editor-label">
@Html.LabelFor(model =>model.Gender)
</div
>
<
divclass
="editor-field">
@*@Html.EditorFor(model =>model.Gender)
*@
@
Html.RadioButtonFor(model =>model.Gender,"Male",true) Male  @Html.RadioButtonFor(model
=>model.Gender,"Female",false) Female
@Html.ValidationMessageFor(model =>model.Gender)<br/>

</div>

@*
<div class="editor-label">
@Html.LabelFor(model =>model.Cab.BookTime )
</div>
<div class="editor-field">
@Html.EditorFor(model =>model.Cab.BookTime)
@Html.ValidationMessageFor(model =>model.Cab.BookTime)
</div>
*@

<divclass
="editor-label">
@Html.LabelFor(model =>model.Cab.JourneyTime )
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.Cab.JourneyTime)
@Html.ValidationMessageFor(model =>model.Cab.JourneyTime)
</div>

@*
<div class="editor-label">
@Html.LabelFor(model =>model.Cab.BookId)
</div>
<div class="editor-field">
@Html.EditorFor(model =>model.Cab.BookId)
@Html.ValidationMessageFor(model =>model.Cab.BookId)
</div>
*@
<p
>
<
inputtype="submit"value
="Create"/>
</
p
>
</
fieldset
>
}
<div
>
@Html.ActionLink("Back to List", "Index")
</div>

Here I have described the Razor file according to my model classes. So if there are any requirements of RadioButton in your mvc3 razor application you can easily see this reference and implement in your application.

Here is the screenshot of my application.



Need ASP.NET MVC 3 hosting? Please visit our site. We specialized in ASP.NET technology. Please email us at
[email protected] if you have further questions.



European ASP.NET MVC 3 Hosting :: How to Create Radio Button in Asp.net mvc3 Razor Application

clock December 16, 2011 10:41 by author Scott

Here I will demonstrate how to use a Radio Button in an ASP.Net Mvc3 Razor File. Just assume, we have a Razor file named Employee details. Where you have to fill in the required employee details. Now in this form we have a "Gender" field name.

You have already created your Model Classes and Controller Classes. So in the Razor file how you will create the Radio Button.

We already know that @Html.Editorfor is for taking input data i.e. Textbox and @Html.Label is for displaying the label control.

Now you have to type @Html.RadibuttonFor just like image below and give the necessary parameters like the code given below.



@
Html.RadioButtonFor(model =>model.Gender,"Male",true) Male 
@Html.RadioButtonFor(model =>model.Gender,"Female",false) Female


Here the Radiobutton takes 3 parameters.

1. The attribute of your Model Class. For mine it is gender.

2. The passing value when you click the particular RadioButton. For my case when you click the 1st RadioButton and click the Submit Button. In the database it will save "Male".

3. By default which RadioButton will be selected? For mine in the case that the first RadioButton name "Male" will be selected.

Here I am giving the complete code for the Razor File. I hope You will get some information from here.

@model
CabAutomationSystem.Employee
@{
ViewBag.Title = "Create";
}
<h2>Create</h2
>
<
scriptsrc="@Url.Content("~/Scripts/jquery.validate.min.js")"type="text/javascript"></script
>
<
scriptsrc="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"></script
>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset
>
<
legend>Employee</legend>

<divclass="editor-label">
@
Html.LabelFor(model =>model.EmployeeName)
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.EmployeeName)
@Html.ValidationMessageFor(model =>model.EmployeeName)
</div>

<divclass
="editor-label">
@Html.LabelFor(model =>model.EmployeeID)
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.EmployeeID)
@Html.ValidationMessageFor(model =>model.EmployeeID)
</div>

<divclass
="editor-label">
@Html.LabelFor(model =>model.ProjectName)
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.ProjectName)
@Html.ValidationMessageFor(model =>model.ProjectName)
</div>

<divclass
="editor-label">
@Html.LabelFor(model =>model.Gender)
</div
>
<
divclass
="editor-field">
@*@Html.EditorFor(model =>model.Gender)
*@
@
Html.RadioButtonFor(model =>model.Gender,"Male",true) Male  @Html.RadioButtonFor(model
=>model.Gender,"Female",false) Female
@Html.ValidationMessageFor(model =>model.Gender)<br/>

</div>

@*
<div class="editor-label">
@Html.LabelFor(model =>model.Cab.BookTime )
</div>
<div class="editor-field">
@Html.EditorFor(model =>model.Cab.BookTime)
@Html.ValidationMessageFor(model =>model.Cab.BookTime)
</div>
*@

<divclass
="editor-label">
@Html.LabelFor(model =>model.Cab.JourneyTime )
</div
>
<
divclass
="editor-field">
@Html.EditorFor(model =>model.Cab.JourneyTime)
@Html.ValidationMessageFor(model =>model.Cab.JourneyTime)
</div>

@*
<div class="editor-label">
@Html.LabelFor(model =>model.Cab.BookId)
</div>
<div class="editor-field">
@Html.EditorFor(model =>model.Cab.BookId)
@Html.ValidationMessageFor(model =>model.Cab.BookId)
</div>
*@
<p
>
<
inputtype="submit"value
="Create"/>
</
p
>
</
fieldset
>
}
<div
>
@Html.ActionLink("Back to List", "Index")
</div>

Here I have described the Razor file according to my model classes. So if there are any requirements of RadioButton in your mvc3 razor application you can easily see this reference and implement in your application.

Here is the screenshot of my application.



Need ASP.NET MVC 3 hosting? Please visit our site. We specialized in ASP.NET technology. Please email us at
[email protected] if you have further questions.



European ASP.NET MVC 3 Hosting :: Deploying ASP.NET MVC 3 Application on Shared Hosting Environment

clock December 8, 2011 06:39 by author Scott

This is an error message you can get when you deployed your ASP.NET MVC 3 on shared hosting server:



It is caused by when you install MVC 3 on your local machine, a number of assemblies are registered in the
GAC. MVC 3 needs these assemblies. Unless your web hosting service has installed MVC 3 on their servers (and many haven't, yet), those assemblies won't be there, and you'll see an error similar to the one above.

Solution

As with previous versions of MVC, we suggest you solve this with what we call "
\bin deployment." Bin Deployment is just a fancy term that means "include the MVC assembly (and its dependencies) in your web application's /bin folder." It's not hard to prepare your project for Bin Deployment, but there are a few more assemblies involved compared to MVC 2. I'll show you what you need to do, step by step.

1. Add Explicit References for MVC and Its Dependencies

Your MVC app's project probably won't have references to all of the assemblies it needs, because they're in the GAC. So you need to add them. Here is the list (they'll all be available in the .NET tab of the Add Reference dialog):


- Microsoft.Web.Infrastructure
- System.Web.Helpers
- System.Web.Mvc
- System.Web.Razor
- System.Web.WebPages
- System.Web.WebPages.Deployment
- System.Web.WebPages.Razor








2. Change Each Reference's Copy Local Property to True

After adding the references, you need to set the Copy Local property for each of the references you just added to True, as pictured below



3. Re-Build and Deploy as You Normally Would

Now, when you build your app, the MVC assembly and its dependencies will be copied to the /bin directory, allowing you to deploy as you normally would.

If you need ASP.NET MVC 3 hosting, please visit our site at http://www.hostforlife.eu. We are Microsoft certified partner and this information you can get it from http://www.microsoft.com/web/hosting/home. We are specialized in Windows Hosting which server European market.



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