Blog Home  Home Feed your aggregator (RSS 2.0)  
Mayur's Blog - Thursday, November 15, 2012
# Thursday, November 15, 2012

I am putting together a code snnipet which you can use to create an extended method for any controller in Asp.Net MVC. This method can look into the views, add in model to the views and send a btye stream with application content of PDF type. As all modern browser can understand this type of byte stream, these browsers are able to read the byte stream and show the PDF in browser window.

In your base controller add in the following method. You inherit other controllers from this base controller

public PDFContentResult RenderPDFUsingHTML(string viewName, object model)


StringWriter sw = new StringWriter();

RazorViewEngine rv = new RazorViewEngine();

ViewEngineResult vr = rv.FindPartialView(this.ControllerContext, viewName, false);

ViewData.Model = model;

ViewContext vc = new ViewContext(this.ControllerContext, vr.View, ViewData, TempData, sw);

vr.View.Render(vc, sw);

string s = sw.GetStringBuilder().ToString();

/*I am using iTextSharpt to convert raw html into PDF. The following GetHTMLToPDFBytes(s) is implementation of itextSharp. You can also use anyother utility to convet html string into PDF.*/

byte[] pdfByes = GetHTMLToPDFBytes(s);

/*PDFContentResult is a custom ActionResult type. See the following code snippet for the details*/

return new PDFContentResult(pdfByes, "application/pdf");



public class PDFContentResult : ActionResult


private readonly string contentType;

private readonly byte[] contentBytes;

public PDFContentResult(byte[] contentBytes, string contentType)


this.contentBytes = contentBytes;

this.contentType = contentType;


public override void ExecuteResult(ControllerContext context)


var response = context.HttpContext.Response;



response.ContentType = this.contentType;

using (var stream = new MemoryStream(this.contentBytes))







Code snippet is self explantory. RenderPDFUsingHTML takes name of view and model as argumets of the method signature. It tries to find out required RazorView based on the given view name, once it is found it inserts the model data to it. Once this is done, it converts the view (raw html) to string, sends this string to iTextSharp to build byte array of PDF.

To make things sipmpler it returns PDFContentResult which is cutom ActionResult type. This is responsible to create a required http response with byte array added to it.

You do the following in your controller to get PDF. Make sure that you first inherit your controller with base controller where you put in the above code snippet. 

public ActionResult GetMyPDF(MyModel model)


..... do coding ...... for controller ........

return RenderPDFUsingHTML("MyViewName",model)


It is good practice to create another view, which is a simplified version of the original view. Generally the views, which we use for web sites are little complicated as it holds html control such as buttons, dropdown menus, and javaScripts etc. We really do not show them in PDF reports. So the simplified veiw takes the same model but removes not needed javaScripts and other html controls.

Thursday, November 15, 2012 6:07:46 PM UTC  #       | 
# Wednesday, October 31, 2012

Today I wondered why the values inserted by jQuery date picker were not properly parsed by default ASP.NET MVC model binder. I discovered that date picker was following US format (mm/dd/yyyy); however, model binder was following the UK format (dd/mm/yyyy).

I thought to override the model binder for dateTime type. Then I thought it may be too much work and there has to be some easier way. I started looking into ASP.NET MVC web.config structure and found that I could specify the current culture.

I added the following <globalization> element to the <system.web></system.web>






It solved my problem and model binder was able to parse the date picker's value and model was properly filled in with required dateTime values.

Wednesday, October 31, 2012 10:44:23 PM UTC  #       | 
# Wednesday, September 28, 2011

Nice article regarding HttpContext. Very useful if you are looking forward to know where to use Application_BeginRequest event available in the Global file

protected void Application_BeginRequest(Object sender, EventArgs e)

Refer this link:

Happy Coding!

Wednesday, September 28, 2011 2:31:47 PM UTC  #       | 
# Saturday, September 24, 2011

If you every wonder about the VIEWSTATE especially in terms of its security, then this may be a good article

Please have a look. I'm sure there is a lot to learn from here.

Saturday, September 24, 2011 2:16:23 PM UTC  #       | 
# Tuesday, August 23, 2011

I converted my web application from .NET 3.5 to .NET 4.0 and ported it to IIS 7.0. All of a sudden the AutoComplete Extender stopped working.

After some research I found that my web.config file needed the followings:



<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>



I added these handlers and the AutoComplete Extneder was back to work.

Hope this may help others to solve the similar problems.

Happy coding to everyone !!

Tuesday, August 23, 2011 7:00:46 AM UTC  #       | 
# Monday, August 31, 2009

Many times we need to refresh/reload a parent window with respect to events associated on child window. For example,

1. Parent web page shows values from database.

2. An end user presses a button on the parent window. It pops up a new child windows; where the end user enters new values for database records

3. The end user presses submit button on child window. It processes code behind and updates database and closes child window after showing a relavant message.

In this situation it is a good idea to refresh the parent web page as soon as the child page is closed. This way the data on parent web page are get refreshed and the end user can get confirmation of recent chages.

The following small javaScript code will help you to achieve that.

<script type ="text/javascript" >

function refreshAPage() {


window.opener.location.href = window.opener.location.href;

//OR window.opener.location.href="URL";



Monday, August 31, 2009 11:14:59 PM UTC  #       | 
# Friday, June 26, 2009

If you are struggling with above mentioned errors and have already gone through your web.config file. Also repaired/installed .NET framework (any version) with service pack (any version). Also tried with repairing/installing ajax toolkit (any version). And still not getting rid of these errors then you might want to try the following. It worked for me!

My local machine worked very well when I was developing an ajax enalbed web site. However, as soon as I put it on production server (Win Server 2003, IIS 6.0 with .NET Framework 3.5 and service pack 1), it started showing errors: Ajax client-side framework failed to load, 'Sys' is undefined etc. However, web site worked but Ajax functionality never worked.

After long effort and going through various docs. I found that I needed to add .axd file extension mapping on IIS. So on my IIS manager I right clicked on my web site; then on the dialogue box I clicked on virtual directory and then clicked on "Configuration" button. On the new dialogue box I clicke on "Add" and tried to add .axd extension which points to the aspnet_isapi.dll. The following is locaton of DLL on my machine. So I added the following path and clicked "OK"


And guess what the result was. The great relief! I spent more than 5 hours. However, at the end of the day I was happy that my ajax enalbed web site was up and running.

I am posting it here and hoping that it might help someone who is facing similar problems.

Have a great computing!

Friday, June 26, 2009 7:43:03 PM UTC  #       | 
# Monday, May 11, 2009
No Table!, No Label!.

A new approach to generate dynamic drop down menu with only span, div and CSS. Of course JavaScript handles all events. (there are other menus out there; ASP.NET has its own built in menu, however, this is my own, no copy and no paste from others, no copyright infringements)

Within few days I will adorn it with VS 2008's built in Ajax Toolkit! Ahh... looking for that, can't wait

Visit here

Monday, May 11, 2009 8:53:46 AM UTC  #       | 
# Saturday, May 9, 2009
Windows vista except ultimate edition does not support SMTP server in IIS (It is true to the best of my knowledge. If you know how to set it up from control panel, please comment this posting).

In case your are looking for a temporary solution then you can download this free SMTP server.

Hope it should help someone like me not able to install SMTP sever by using control panel in vista.

Saturday, May 9, 2009 7:46:38 PM UTC  #       | 
# Friday, May 8, 2009

First time I went through these confusing names and found some information about them and thought to display on my blog so that it will be useful to others.

CurrentUICulture sets your UI language ( i.e. it translates 'tool tips', 'menus', 'helps' etc in a specified language)

CurrentCulture sets your default user locale (i.e. format of date, currency, format of time etc; there are approximately 208 locales in vista. So it displays $10,000 for 'en-US' and £10,000 for 'en-GB')

You can visit this little app to get an idea

In this app the calendar language is traslated by CurrentUICulture, while currency is formatted by CurrentCulture.

For more info visit this blog:

Wondering how to set it up! The following might give you a little idea.

Make sure that you are importing namespaces for system.threading and system.globalization into your code. The following code instructs run time to change current thread's culture based on the given input. InitializeCulture is a method of page class.

 protected override void InitializeCulture()




        string lang = "hi";


        /*I have hardcoded language to Hindi, "hi" stands for Hindi;

        you can also set it up programmatically */            


        if (lang != null && lang != "")


            Thread.CurrentThread.CurrentUICulture  = new CultureInfo(lang);

            Thread.CurrentThread.CurrentCulture = 




Friday, May 8, 2009 11:45:24 PM UTC  #       | 
Copyright © 2022 Mayur Bharodia. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: