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



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:



European ASP.NET MVC 3 Hosting :: Error handling in ASP.NET MVC3

clock November 23, 2011 07:42 by author Scott

In ASP.NET MVC (versions 1 to 3) we have the [HandleError] attribute, that will allow us to handle errors in a very easy way.

Just by decorating an action (or controller if we want to extend HandleError behaviour to all actions on that controller) with the HandleError attribute and enabling “CustomErrors” in web.config, we get a nice redirection to a friendly view in case an unhandled error raises.

Internally, we could have a look at the implementation of OnException method inside HandleError using Reflector to see how it works:



As we can see, the unhandled exception will be handled if it hasn't been already marked as "handled" and if custom error handling is enabled .

Web.config customErrors section

The CustomErrors section allow us to define automatic error handling behaviour. If it doesn't exists, it must be created inside system.web section. as shown here:




Posible values for mode are "Off | On | RemoteOnly". This will allow us to easy define behaviour for development and production scenarios :

·         On: custom error handling enabled

·         Off: custom error handling disabled. If an error is raised, we will see the yellow screen of death of ASP.NET

·         RemoteOnly: if we launch the application in the local server (targeting http://localhost ), we won't see custom errors. If we access the application from other machine, we will see custom erros. This option is used by developers to debug applications. If there is an error, you can always (among other things) RD to your server and launch the application in a local browser so you see the exception in a first seat.

Behaviour:

·         If we use the HandleError attribute and CustomErrors is enabled, when an unhandled error raises, the MVC runtimewill look for a “Errors.aspx” view in the context of the HttpRequest being processed (current view folder associated to controller or shared view folder), and will render it. In this case the "defaultredirect" and "redirect" CustomErrors attributes are ignored

·         If we don't use the HandleError attribute and CustomErrors is enabled , we will get an HTTP redirection to the url defined on the "redirect" and "defaultredirect" attributes, within the CustomErrors section in web.config (in our case, /Error/General

Important: ASP.NET MVC3, registers the HandleError attribute globally (for all controllers) !! (see image). Take that into account so you don't think your MVC3 controlleris not using the HandleError attribute (by default it is). In previous versions of  ASP.NET MVC, where we didn't have global filters, the HandleError attribute had to be defined manually for each action or controller.



Also important: If you have enabled CustomErrors=On , also added the [HandleError ] and still get a yellow screen of death please make sure the Error.aspx has no errors (check master page and the errors.aspx code) , it may have an error (this is pretty common scenario and difficult to debug).You can check if this is happening simple by temporaly removing all Error.aspx code and replacing by a text (más información).

To avoid showing ASP.NET yellow screen of death if your Error.aspx has errors, use "redirect" CustomErrros attribute to show a static  html page.



Controller OnException

Alternatively to HandleError, we can also override the OnException  method of a controller (or all of them if we use a base controller class).

An example of exception handling, logging and redirection to friendly message would be:



Note: the OnException event is executed independly of the use of HandleError in the controler.

Using Elmah to intercept, log and notify of unhandled errors

Elmah is a fantastic library that help us to intercept, register (in the desired format: database, text file, xml, etc) and optionally deliverunhandled errors ocurred in our application, so we keep everything in control at all times. It also provieds a web interface so you can access the error records remotely, and a RSS feed so you can subscribe with your favorite RSS reader.



With NuGet , a library package manager, available with ASP.NET MVC3, install Elmah is a pretty straightforward process. First step is launching NuGet:



Then, we search for "Elmah":



and proceed to install it. NuGet will handle for us the necessary steps required to install and configure it (in previous versions of ASP.NET MVC we had to do it manuall). NuGet does for us:

·         downloads the last version from the oficial repository

·         adds the assembly reference to our project

·         modifies the web.config to add the proper configuration parameters

In our case, Elmah needs some parameters and configuration sections (httpModules,httpHandlers, etc)  in order to work del web.config :



If we want Elmah to record errors or events in XML files inside a certain directory , we have to indicate it::



And that's it.. When an unhandled error is raised, Elmah will be able to intercept it and record it, and also send an email to the administrator. 

Registering with Elmah custom events and errors

Elmah offers an API so we can record or own events or exceptions . We can use that funcionality to log exceptions that we have already handled with our code. Example:



Elmah and HandleError


Elmah works perfectly with unhandled exceptions (yellow screen of death), but won't be able to intercept exceptions that are being handled by the [HandleError] attribute.

To fix this, we need to create a custom HandleError attribute and add a custom behaviour to the new attribute.



More details and source code here: 
http://stackoverflow.com/questions/766610/how-to-get-elmah-to-work-with-asp-net-mvc-handleerror-attribute 

Filtering unwanted events in Elmah

If Elmah is logging too many stuff, (ex: 404 errors looking for favicon.ico), I have the posibility of applying custom filters to those unwanted events .

First, we must add the Elmah ErrorFilter module to web.config:



Once registered, we implement the following events on Global.asax.cs, defining the filtering rules I want to apply:



Final notes

In my particular experience, I found the best practice to use the custom HandleError as shown in the last part of this article (having the HandleError applied globaly) with CustomErrors enabled, helped by Elmah to handle, register and send unhandled exceptions . When necessary, I use the Elmah signal capabilities for those handled exceptions I want to log.



European ASP.NET MVC 3 Hosting :: RenderBody, RenderPage and RenderSection in ASP.NET MVC 3

clock November 11, 2011 05:27 by author Scott

Everybody knows Razor is the new view engine ASP.NET Web Pages, so I thought I’d write about some Razor syntax you may not be aware of. The three methods I’ll be focusing on today are RenderBody, RenderPage and RenderSection. You’ll need to understand how each of these work if you want to get know the Razor syntax intimately. 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 them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. Now it's time to start coding! I’ll begin with the RenderBody method.

RenderBody

The RenderBody method resides in the master page, or in Razor this is commonly referred to as the Layout page. There can only be one RenderBody method per Layout page. If you’re from Web Forms world, the easiest way to think of RenderBody is it’s like the
ContentPlaceHolder server control. The RenderBody method indicates where view templates that are based on this master layout file should “fill in” the body content.



RenderPage

Layout pages can also contain content that can be filled by other pages on disk. This is achieved by using the RenderPage method. This method takes either one or two parameters. The first is the physical location of the file, the second is an optional array of objects that can be passed into the page. Add a new cshtml file to the Shared folder and call it _Header.cshtml. I've prefixed this file with an underscore because I don't want this file to be called outside of RenderPage. By default, ASP.NET will not serve pages beginning with an underscore. Here's the code I'm adding to the _Header.cshtml page.


<h1>Header Here</h1>

And to use this in the layout, it's as easy as this.



RenderSection


Layout pages also have the concept of sections. A layout page can only contain one RenderBody method, but can have multiple sections. To create a section you use the RenderSection method. The difference between RenderSection and RenderPage is RenderPage reads the content from a file, whereas RenderSection runs code blocks you define in your content pages. The following code illustrates how to render a footer section.



RenderSection expects one parameter and that is the name of the section. If you don’t provide that, an exception will be thrown. Views can add data to sections by using the following code.



If you ran the website now it’ll run without error. If on the other hand you don’t include the section footer in the view, you’ll get an error.



That’s because by default, sections are mandatory. To make sections optional, just add the second parameter, which is a Boolean value.



Now things will run just fine.

These three methods you will use time and time again when you're using the Razor view engine. This code works both for ASP.NET MVC 3 and also WebMatrix. Have fun!



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