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



European ASP.NET MVC 3 Hosting :: RenderPage And Data in ASP.NET MVC 3 Web Pages

clock December 6, 2011 07:16 by author Scott

When you’re working with MVC, you sometimes work with partial views. With the new Razor view engine, partial views can be called through the RenderPage method. RenderPage renders the content of one page within another page. What isn’t obvious from the beginning is how to access data that is passed into the partial page. I thought I’d do a quick article and show you how. This code also works in WebMatrix if you're using it.

Before moving on, you need to download ASP.NET MVC 3.
Click here to download and install it using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. For this example, my model will be a list of processes running on your machine. I want to pass that model into the view, and then pass that model into the partial page. When you’re working with partial views, you need to specify a path to the view, then an optional array of data to the page being rendered. The array of data can be accessed by using the
System.Web.WebPages.WebPageBase.PageData property. Here’s the model for the view.



And here’s the view.



I’m going to create a partial view called _DisplayProcess and call it via the RenderPage method. When I create partial views I always prefix them with an underscore so they can only be rendered as a partial view. By default ASP.NET won’t render files beginning with an underscore. The second parameter for RenderPage is the array of data. To use this, you can use the PageData property.



If you only had a single object being passed into the page, you would reference it like this.



To me it wasn’t obviously the first time I used partial views in Razor, so hopefully if you get stuck like me, this helps you out.



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

clock December 5, 2011 08:42 by author Scott

In this application I will create a Blog post with post comments application. This application will be Object Class Mapping using Entity Framework. That means with the mapping of classes the database and table will be created automatically.

Step 1:

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

Step 2:

Now under the "Model" Folder create two classes.

·         Blog

·         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 we did 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" keyword 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 also we have the object reference of the "Blog" class. Before that I have used the virtual keyword.

Step 5:

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

Create the "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 add a Reference for the Entity Framework by clicking "Add New Reference" under the project.



In my project I already added the reference. Without this dll the table will not be created in the database by object class mapping.

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

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 comments class. The Dbset table will be created 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 method in the Controller class.





Step 9:

Now in the "HomeController" class first create the object of class "BlogDbContext":

    BlogDbContext _db = new BlogDbContext();

After that in the Index Method write the following code:

public ActionResult Index()
        {
            var GenreLst = new List<string>();
 
            var GenreQry = from d in _db.Blog
                           orderby d.BlogName
                           select d.BlogName;
            GenreLst.AddRange(GenreQry.Distinct());
            ViewBag.movieGenre = new SelectList(GenreLst);
 
            return View(_db.Comments .ToList ());
 
        }

See here I selected all the Blog Name from and after that adding into the list.

Then through "ViewBag" I am passing the GenreLst.

Step 10:

Now create a master page in the razor engine under the "shared" folder. Give 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 view. It will look like:



Please check "Create Strongly-typed Views".

Choose Model Class "Comments" under DropDownList.

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 the code for the list view automatically.

Paste the following code there.

@model IEnumerable<blogmvc3.Models.Comments>
 
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
 
<h2>Index</h2>
 
<p> 
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <@*th>@Html.ActionLink("Search Blog", "SearchIndex")</th>*@
        <th>
            Blog Name :
        </th>
        <th></th>
        <th>
           Description :
        </th>
        <th></th>
        <th>
           Body
        </th>
        <th></th>
        <th>
            Comment :
        </th>
        <th></th>
        <th>
        BlogNAme List: @Html.DropDownList("movieGenre", "All"); 
       </th>       
    </tr>
 
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.CommentId }) |
            @Html.ActionLink("Details", "Details", new { id=item.CommentId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.CommentId })
        </td>
       
        <td> @item.Blog.BlogName</td>
         <td> @item.Blog.Description</td>
          <td> @item.Blog.Body</td>      
        <td>
            @item.Comment
        </td>       
    </tr>
}
</table>

Now see the code BlogNAme List: @Html.DropDownList("movieGenre", "All");

Here "Html.DropDownList" is accepting the MovieGenre which I passed through view bag and 2nd parameter is to display all the list.




Now run the Code it will look like the following figure:



About HostForLIFE.eu

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

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in