ASP.NET MVC 1.0 Html.CheckBox() outputs a hidden field?

by Graffen 1. December 2009 11:41

I just stumbled over a funny little thing in the HTML output from the Html.CheckBox() helper method in ASP.NET MVC 1.0.

In my .ASPX file, I had defined a checkbox like this

<%=Html.CheckBox("MyCheckBox") %>

 
This resulted in the following HTML output:

<input id="MyCheckBox" name="MyCheckBox" type="checkbox" value="true" /><input name="MyCheckBox" type="hidden" value="false" /> 


A bit stumped as to why I got an extra hidden field, I decided to have a look in the ASP.NET MVC source code and found the following comment:

if (inputType == InputType.CheckBox) {
    // Render an additional <input type="hidden".../> for checkboxes. This
    // addresses scenarios where unchecked checkboxes are not sent in the request.
    // Sending a hidden input makes it possible to know that the checkbox was present
    // on the page when the request was submitted.
...

This is really quite logical. The reason it works is that the first time a browser hits an element with a value attribute, the parser will ignore all subsequent elements with the same name. This way, we’ll always get a result back to our controller containing all the checkboxes that are present on the page, no matter if they are checked or not.

Tags: ,

.NET | Programming | ASP.NET MVC

Follow up on my blade server adventures

by Graffen 24. April 2009 11:50

I promised to follow up on my adventures in using shared storage for hosting data being served by a cluster of blades. Unfortunately we don’t (yet) have a nice SAN or anything like that, so all I had access to was a simple Windows file share on a NAS (I love three letter acronyms!). I couldn’t get over the concurrence problems I faced, and servers were constantly tripping over each other giving me file locking errors and stuff like that.

So I ended up spending a day writing a small deployment application that could copy the code out to all the blade servers. What my tool does is this:

 

  1. Copy an App_Offline.htm file to the root of all web servers. The App_Offline file shows a message to users that we are upgrading and that we’ll be right back.
  2. Copy latest build from the build server to each blade
  3. Modify web.config to disable debug, fix connection strings etc
  4. Remove App_Offline from all blades.

 

All in all this ends up working really well and is easy to work with. Also, it allows me to easily hand over the deployment task to someone else, as this person only needs to install the small click-once deployment tool.

 

image

Tags:

.NET | Programming | Utilities and Tools

Serving an ASP.NET website from a network share in IIS

by Graffen 12. March 2009 10:04

At work I’ve spent the past couple of days getting our production environment ready for a new product. The servers are a series of old HP blades with an Alteon load balancer facing the world. I wanted to be able to publish the application to one place and have all the servers serve it from there. So I got the IT department to supply me with a network share and I started setting up the IIS servers.

I quickly stumbled upon a problem: ASP.NET requires certain security settings to be allowed to execute code located on a network share. After googling around a bit, I found the solution to be quite simple. On each server, simply run the following in a command prompt:

 

c:\windows\microsoft.net\Framework\v2.0.50727\CasPol.exe -m -ag 1 -url "file:////\\servername\share\*" FullTrust -exclusive on

Remember to replace servername and share with your own settings.

 

UPDATE: Okay so this wasn’t the greatest idea. Like Mr. Viehweg noted in his comment, I hit file-locking issues almost right away. Looking into Distributed File System now.

Tags:

Other computer stuff | .NET

Holiday time again and a very short update

by Jesper Hess Nielsen 29. June 2008 07:57
In a few hours I'll be flying to Vienna before heading on to Postojna (Slovenia), Venice, Trieste and ultimately, Amsterdam where I will be taking part in Sensation White. I haven't been blogging much at all lately. Things have been really hectic at work so I haven't really been able to find the time.

I've started working on a new version of my free SubVersion hosting system. The frontend will be done using the new ASP.NET MVC Framework and I hope to get the backend a bit more "enterprise-like" - probably by using message queueing and/or WCF to pass notices between the frontend and backend. We'll see. I haven't decided 100% yet.

Oh - and yesterday I decided to start using Twitter much more actively. I already have a couple of followers but feel free to add me. I've installed Twibble on my N95 8GB, so everywhere I have Internet access I should be able to update.


Tags:

.NET | Blogging | Day to Day | Programming | SubVersion | Vacation

PageRequestManagerParserErrorException - Part 2 (hack)

by Graffen 3. January 2008 09:53
Wow! Finally! By chance I stumbled across another blog post on the web, where a solution (or temporary fix until something better turns up) to my ongoing PageRequestManagerParserErrorException problems.

Basically the problem is that on a page where I use the Microsoft AJAX.NET framework, I get intermittent popups when viewing the pages in Firefox. The popups contain the nice, short, concise error message "Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write, response filters, HttpModules or server trace is enabled. Details: Error parsing near ''"

Now I finally found someone who came up with a simple yet effective hack to mask/solve the problem. The solution involves adding some Javascript to your pages and then overriding the OnInitCompleted method on the server side.
Here's the JavaScript code:

<script type="text/javascript" language="javascript">
window.isFireFox = (navigator.userAgent.indexOf("Firefox") != -1);


if(window.isFireFox)
{
        window.addEventListener('load',OnPageLoad,false);
        function OnPageLoad()
        {
                 Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(OnBeginRequest);       
        }

        function OnBeginRequest(sender, args)
        {
                var delta = args.get_request().get_headers()['X-MicrosoftAjax'];    
                if(delta == 'Delta=true')    
                {
                    var body = args.get_request().get_body() + 'X-MicrosoftAjax=' + encodeURIComponent('Delta=true');        
               args.get_request().set_body(body);    
                }
         }
}
</script>


 

And here's what goes in your codebehind:


 
protected override void OnInitComplete(EventArgs e)
{
  #region Firefox Fix

  ScriptManager sm = ScriptManager.GetCurrent(this);
  if (IsPostBack && Request.Browser.Browser == "Firefox" &&
   sm != null &&
   sm.IsInAsyncPostBack == false &&
   Request.Form["X-MicrosoftAjax"] == "Delta=true")
  {
    sm.GetType().GetField("_isInAsyncPostBack",
      System.Reflection.BindingFlags.NonPublic |
      System.Reflection.BindingFlags.Instance).SetValue(sm, true);
  }
  #endregion
  base.OnInitComplete(e);
}


Lo, and behold, it seems to work! Thanks to M. Bhaskar for the solution!

Tags:

.NET | Programming | The Web

Restoring Visual Studio 2008 IntelliSense

by Jesper Hess Nielsen 26. November 2007 13:34

After installing VS2008 last week, I noticed that my IntelliSense wasn't working. This is something really annoying to a person who has always relied heavily on IntelliSense while coding.

I searched the web a bit and came across this blog entry. This solution worked perfectly for me. Here's a quick walkthrough.

  1. Hit Tools / Options in your Visual Studio.
  2. On The Left Tree click Text Editor / All Languages.
  3. Under Statement completion ensure that “Auto list members” is checked with a tick mark. (Make sure that this option is fully selected and not partly selected)
  4. Under Statement completion ensure that “Parameter information” is also checked with a tick mark. (Make sure that this option is fully selected and not partly selected)

Nice and simple :-)

Tags:

.NET | Programming

Generating good looking PDF files on the fly from C#

by Jesper Hess Nielsen 23. November 2007 07:42

Wow! I really need to get better at updating my blog with interesting little articles about this and that. Here's one example that I've been working with over the past two weeks.

A short background
The company I work for, Infopaq International, is a media watch company and delivers news clippings to customers in one of several formats. One possibility is (in the countries that allow this because of copyright legislation) to provide E-clippings in a PDF file.

And then...
Until now, this PDF file has been really simple with nothing but our logo at the top and the clipping centered on the page. I was asked to look into how we could beautify these e-clippings so they would be more aesthetically pleasing and also contain more information. For example, information about the customer, the media from which the clip came, etc. My colleague in Stockholm sent me a mock-up of how he would like the final PDF to look, and I set about figuring out how to get the job done.

The old solution was built using iTextSharp so i decided to have a closer look at what functionality was available in this library. I set off to try to programmatically build a PDF file the way my Swedish colleague wanted but soon discovered that this really wasn't as easy as I first had hoped. At least I found it to be quite challenging to get things to align just the way I wanted them to.

So I put my thinking cap back on and started to ponder what else could be done. After a bit of reading, a bit of Googleing and a lot of staring at iTextSharp, I decided to go for a different approach. I installed Adobe Acrobat and set off to design my PDF using a real PDF authoring utility. I thought (wrongly, by the way) that I could simply define some fixed strings in the template which I then could search-and-replace with data from my database. It turned out that PDF just doesn't support that possibility. But then it struck me. I remembered reading somewhere about filling out PDF forms from iTextSharp. I Googled a bit and decided to give it a try.

I designed a PDF form using Adobe LiveCycle Designer and assigned meaningful names to all the fields (there are about 30 fields in total on the form). Now it was only a question of using iTextSharp to fill out the fields and then spit out the finished result to the client. And now for some code:

// Open the template PDF file
PdfReader rdr = new PdfReader(HttpContext.Current.Server.MapPath("~/App_Data/Template.pdf"));
// _outStream is a HTTP Response Stream
PdfStamper stamper = new PdfStamper(rdr, _outStream);
// Grab our fields
AcroFields fields = stamper.AcroFields;

// And then a whole load of these (in this case reading the department name from XML):
fields.SetField("InfopaqCompanyName", departmentNode.SelectSingleNode("departmentname").InnerText);
(...)

(...)
// Close our stamper
stamper.FormFlattening = true;
stamper.FreeTextFlattening = true;
stamper.Close();

And that's just about all there is to it :)

Tags:

.NET | Programming

PageRequestManagerParserErrorException when using Microsoft .NET AJAX UpdatePanels

by Jesper Hess Nielsen 13. July 2007 07:13
For the past couple of weeks, I've been fighting with a really strange error when using UpdatePanels on my websites. It seems that if a page stands idle for too long ("too long" is variable - sometimes it's a few seconds, other times it's minutes), I get a JavaScript popup with a PageRequestManagerParserErrorException message. Apparently the error only appears in FireFox!

The error message states something about it being caused by Response.Write(), HTTPHandlers or any other things that might change the output stream, thereby corrupting the AJAX request. I searched through my code and couldn't find any of the mentioned causes.

Now this morning, I decided to do a simple test. I've created an aspx page containing an UpdatePanel, a Timer and a Label. On the tick event of the timer, I just update the label with the current date and time. Simple and a "schoolbook" example of what AJAX can do.

When I run the page, the label starts updating. Now if I wait for long enough (again, variable), I get the exact same error message. So it turns out that it has nothing to do with page complexity, several UpdatePanels or anything like that. It's a general error.

After searching the web for likely solutions (or causes, so I could find my own solution), I've pretty much given up. Does anyone know what might be causing this error? I've attached my simple website so you can see what I've done. ANY feedback is greatly appreciated!

AJAXEnabledWebSite.zip (2.36 KB)

Tags:

.NET | Programming | The Web

Wow, it's actually being used!

by Jesper Hess Nielsen 13. June 2007 19:57

Back in December, I posted an entry about a little skunkworks project I'd been working on. It's a hosting service for SubVersion repositories. I just checked the user database to see how many users there were and was pretty surprised at the number. I guess that means I'll have to take up the project again and polish off a few of the rough corners. Since I published the original version, I've also got a few new ideas about how I could implement some of the stuff in a cleverer way. Once I get the code cleaned up a bit, I'll post the entire source code in its own SVN repository. That way, it'll be easier for you guys out there to change and improve it :-)

Feel free to add a comment here if you're using the service and want to give me feedback - it'll be greatly appreciated!

(Oh, and thanks Allan for the blog post - you've caused a couple of new users to sign up as well ;-))

Tags:

.NET | SubVersion

Setting the Visible property on a web control

by Jesper Hess Nielsen 25. March 2007 16:04

Another little thing that I stumbled across - when trying to hide a control from anonymous users, I just tried the following:

Visible='<%#Page.User.Identity.IsAuthenticated %>'

Now I would have expected that to just work. But when I viewed my page, the controls were still visible. After a bit of trial and error it occurred to me that the <%# syntax is used when databinding. So in my Page_Load method, I just called myControl.DataBind(); and everything worked perfectly.

Tags:

.NET | Programming | The Web

Copyright © 2009 Jesper Hess Nielsen. This work is licensed under the Creative Commons License.
Powered by BlogEngine.NET 1.5.0.7
Theme by Extensive SEO

About the author

A blog about me, R/C planes, .NET, Twitter and whatever else I feel like writing about.