How to use HandleError in MVC 3 [With Example]

To enable custom errors, we’ll need to set the customErrors property to ‘on’.

1. Web.config

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

2. Exception in controller

Below in the controller, the controller class is decorated with the HandleError attribute and I have thrown an exception to test this out.

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        throw new Exception("Error Occured !");
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

3. Error.chtml

In the screenshot below, I have added a razor view Error.cshtml, do note that this view uses a model of type System.Web.Mvc.HandleErrorInfo.

enter image description here

@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; }
<h2> Sorry, an error occurred while processing your request. </h2>

Now when we run the project and the exception we wrote will be raised, but instead of getting the YSOD we now get the following customized error message.

enter image description here

We can customize this view and get more meaningful message to our fellow devs in the following manner…

@model System.Web.Mvc.HandleErrorInfo 
@{ ViewBag.Title = "Error"; }
<h2> Sorry, an error occurred while processing your request. </h2> 

@if (Model != null)
{
    <p>Controller Name: @Model.ControllerName</p> 
    <p>Action Name : @Model.ActionName</p> 
    <p> 
        <p>Exception Details: @Model.Exception.Message</p> 
        <p>Source:@Model.Exception.Source</p> 
        <p>Stack Trace:@Model.Exception.StackTrace</p> 
        <p>InnerException:@Model.Exception.InnerException</p>
    </p>
}

and the output

enter image description here

Hope you found this helpful !

Introduction to WebGrid in MVC 3 Razor (with code samples)

Webgrid is used to display data on a web page using an HTML table element. It has built-in support for paging and sorting. You can style webgrid easily using the alternatingRowStyle,headerStyle or tableStyle attributes.

Here is a link to msdn for the WebGrid Class.

The GetHtml() method renders the grid. Now lets render a simple grid with no formatting using the following code.

1. Basic

Razor Code

@{  
var grid = new WebGrid(source: Model.Products);  
@grid.GetHtml()  
} 

Output

2. Formatting :

Now to make the grid more visually appealing, you can customize each column of the webgrid. This can be done using the optional argument called ‘Columns‘. In the code below for the last column I have used the optional ‘format‘ attribute to place a ‘$’ character after the price value.

Razor Code

@{  
var grid = new WebGrid(source: Model.Products);  
@grid.GetHtml(columns:grid.Columns(  
grid.Column(columnName:"ProductName", header:"Name of the Product"),  
grid.Column(columnName:"ProductCode", header:"Code"),  
grid.Column(columnName:"ProductPrice", header:"Price in $", format:@<text>@item.Price $</text>)))  
}  

Output

3. Sorting and Paging :

For sorting and paging, we can use the ‘rowsPerPage‘ attribute which specifies the maximum number of rows to be displayed per page, we can disable sorting on a specific columns using the ‘canPage‘ attribute on that column. (see Code column)

Razor Code

@{  
var grid = new WebGrid(source: Model.Products, rowsPerPage:4, canPage:true, canSort:true);  
@grid.GetHtml(columns:grid.Columns(  
grid.Column(columnName:"ProductName", header:"Name of the Product"),  
grid.Column(columnName:"ProductCode", header:"Code", canSort:false),  
grid.Column(columnName:"ProductPrice", header:"Price in $", format:@<text>@item.Price $</text>)))  
}  

Output

4. Styling

You can style your webgrid using the alternatingRowStyle,headerStyle or tableStyle attributes, see the code below…

Razor Code

@{  
var grid = new WebGrid(source: Model.Products, rowsPerPage:4, canPage:true, canSort:true);  
@grid.GetHtml(  
headerStyle: "headerStyle",  
tableStyle: "tableStyle",  
alternatingRowStyle: "alternateStyle",  
columns:grid.Columns(  
grid.Column(columnName:"ProductName", header:"Name of the Product"),  
grid.Column(columnName:"ProductCode", header:"Code", canSort:false),  
grid.Column(columnName:"ProductPrice", header:"Price in $", format:@<text>@item.Price $</text>)))  
}  

CSS Code

.headerStyle  
{  
background: #FFFFCC;  
}

.tableStyle  
{  
background: #CFFFCC;  
}

.alternateStyle  
{  
background: #FBFFCC;  
}  

Output

5. Custom Paging

http://yassershaikh.com/webgrid-paging-with-pager-method-in-razor-mvc/

5. How to include an action link in a webgrid

We can include ActionLinks in a webgrid column using the following code. We can also pass values from an ActionLink to a Action as seen in the code below.

grid.Column(format: (item) => Html.ActionLink("Edit", "ActionName", new { param1 = "hello", param2 = "bye" }))  

or

grid.Column(format:@<text>@Html.ActionLink("Edit", "ActionName", new { param1 = "hello", param2 = "bye" })</text>)  

In the code above I am passing two values to my action viz. param1, param2

Action in the Controller

public ActionResult ActionName(string param1, string param2)  
{}  

6. Displaying multiple ActionLink in a single column of a webgrid

grid.Column(header: "Actions", format: (item) =>  
new HtmlString(  
Html.ActionLink("Edit", "Edit", new { id = item.id } ).ToString() +  
Html.ActionLink("Delete", "Delete", new { id = item.id } ) .ToString()  
) 

How to send email in ASP.NET C# MVC 3 (with sample working code)

Below is a sample working code for sending in a mail using C#, in the below example I am using google’s smtp server. The code is pretty self explanatory, replace email and password with your email and password values,

In case of any queries feel free to write in using the comment box. CHEERS !

public void SendEmail(string address, string subject, string message)  
{  
    string email = "yrshaikh.mail@gmail.com";  
    string password = "put-your-GMAIL-password-here";

    var loginInfo = new NetworkCredential(email, password);  
    var msg = new MailMessage();  
    var smtpClient = new SmtpClient("smtp.gmail.com", 587);

    msg.From = new MailAddress(email);  
    msg.To.Add(new MailAddress(address));  
    msg.Subject = subject;  
    msg.Body = message;  
    msg.IsBodyHtml = true;

    smtpClient.EnableSsl = true;  
    smtpClient.UseDefaultCredentials = false;  
    smtpClient.Credentials = loginInfo;  
    smtpClient.Send(msg);  
}  

Custom / Efficient Paging in ASP.NET MVC 3 using Skip() and Take() LINQ methods

Recently, I was required to create custom paging in an MVC 3 application after posting a question at at http://stackoverflow.com/q/11662772/1182982 I was asked to use Skip() and Take() LINQ methods.

So keeping that in mind, below is what I had tried and it worked !

You can download the code from here and run/debug/see for yourself.. http://yassershaikh.com/wp-content/uploads/2012/07/CustomPagingDemo.rar

Product.cs

public class Product
{
    public string ProductName;
    public string CompanyName;
}

Model -> IndexModel

public class IndexModel
{
    public List<Product> Products { get; set; }
}

Controller

public class HomeController : Controller
{

    List<Product> products = new List<Product>()
    {
        // 12 products
        new Product(){CompanyName = "Samsung", ProductName = "Galaxy S III"},
        new Product(){CompanyName = "Samsung", ProductName = "Galaxy S III"},
        new Product(){CompanyName = "Apple", ProductName = "Ipad 3"},
        new Product(){CompanyName = "Karbon", ProductName = "Kaamaal"},
        new Product(){CompanyName = "Warren", ProductName = "Jistern"},
        new Product(){CompanyName = "Kolles", ProductName = "Avenski"},
        new Product(){CompanyName = "lll", ProductName = "bbb7"},
        new Product(){CompanyName = "nnn", ProductName = "bbb8"},
        new Product(){CompanyName = "mmm", ProductName = "bbb9"},
        new Product(){CompanyName = "ttt", ProductName = "bbb10"},
        new Product(){CompanyName = "uuu", ProductName = "bbb11"},
        new Product(){CompanyName = "yyy", ProductName = "bbb13"},
        new Product(){CompanyName = "ooo", ProductName = "bbb12"},
    };

    private const int PageSize = 3;

    public ActionResult Index(int page = 1)
    {
        var productlist = products.Skip((page – 1) * PageSize).Take(PageSize).ToList();
        var model = new IndexModel();
        model.Products = productlist;

        ViewBag.CurrentPage = page;
        ViewBag.PageSize = PageSize;
        ViewBag.TotalPages = Math.Ceiling((double)products.Count() / PageSize);

        return View(model);
    }

    public ActionResult About()
    {
        return View();
    }
}

View – Index View

@model CustomPagingDemo.Models.IndexModel

@{
    ViewBag.Title = "Home Page";
}

<p>
    @foreach (var product in Model.Products)
    {
        <table width="500px">
        <tr>
        <td width="50%">@product.CompanyName</td>
        <td width="50%">@product.ProductName</td>
        </tr>
        </table>
    }
</p>

<!– Page links below -–>
<p>
    @for(int i= 1; i<=ViewBag.TotalPages; i++)
    {
        <a href="@Url.Action("Index","Home", new { page = i } )">@i</a>
    }
</p>

How to handle two submit buttons in Html.BeginForm in MVC 3 Razor

Below is a form with two submit buttons. Note that both these submit buttons have the same name i.e “submitButton”

@Html.BeginForm("MyAction", "MyController"); %>
<input type="submit" name="submitButton" value="Button1" />
<input type="submit" name="submitButton" value="Button2" />
}

Now over to the Controller, the Action takes in an input parameter called string stringButton and the rest is pretty self-explanatory.

public ActionResult MyAction(string submitButton) {
switch(submitButton) {
case "Button1":
// do something here
case "Button2":
// do some other thing here
default:
// add some other behaviour here
}
…
}

Hope this helps you !

How to install and configure SPARK view in MVC 3 using Visual Studio 2010

Step 1 : Download Spark View Engine from here

Step 2 : Add Reference to your MVC project 

Now using the files downloaded, add the following dlls to your project

  • Spark.dll
  • Spark.Web.Mvc.dll

Step 3 : Add the following code to Application_Start in Global.asax file

protected void Application_Start(object sender, EventArgs e)  
{  
var settings = new SparkSettings()  
.SetDebug(true)  
.AddNamespace("System")  
.AddNamespace("System.Collections.Generic")  
.AddNamespace("System.Linq")  
.AddNamespace("System.Web.Mvc")  
.AddNamespace("System.Web.Mvc.Html");

ViewEngines.Engines.Add(new SparkViewFactory(settings));  
}

Step 4 : Add a Spark View

There will not be an option to add a spark view. You will first need to add an .aspx or a razor view and then rename extension (.aspx//cshtml) of the view to .spark

AND that’s it, your spark view is ready to go :D

How to create a Facebook Page

Step 1
Login to facebook, and click this link http://www.facebook.com/pages/create.php

Step 2
Create a Page” like the one below will open up

I have selected the “Cause or Community” option, you can select any other options you like, the rest of the procedure is same for all.

Step 3
Once that is done, you will be required to fill in more details like the box below

Upload an image for the profile picture

add some more information

and thats it. you fb page is created !
Step 4- Most Important Step
Head out to this link http://www.facebook.com/pages/Random-Awesome-Trolls/439050769468583 and like it.

How to Display Total Posts Published Count in WordPress using PHP ?

Today, I wanted to display on my homepage, a total post published count, so after searching for this, I found a very interesting piece of code that does this job, check out the code below…

<?php echo wp_count_posts()->publish; ?>

Below is a cut off from my homepage, where I am displaying a total number of posts published using this very code.

Hope this helps you too