views:

310

answers:

3

Background

I have a web application that uses ISO-8859-1 encoding. When I pass parameters using Html.ActionLink(), the value is decoded to UTF-8:

Web.config:

<globalization requestEncoding="iso-8859-1" responseEncoding="iso-8859-1"
               fileEncoding="iso-8859-1" />

Index.aspx

This is a <%= Html.ActionLink("test", "Read", new { name="Cosméticos" }) %>

generates the following:

This is a <a href="/Intranet/Read?name=Cosm%C3%A9ticos">test</a>

The problem is the value I receive in my controller is UTF-8, not iso-8859-1:

TestController:

public ActionResult Read(string name) {
  //name is "Cosméticos" here!
}

Question

Why the string is not decoded to Cosméticos?

A: 

Does your aspx files are physically saved in iso-8859-1?

"File / Save Xyz As" And click at the right of the save button to have more encoding options to save your file in..

A guess

Mike Gleason jr Couturier
Yes, my files are saved in iso-8859-1. But I don't think this is the problem, because "Cosméticos" is coming from my database.
wmasm
The thing with encodings, it have to strictly be the same across each layer of your app., or be converted from one to another if there's a mismatch between 2 layers. Does your DB is in iso-8859-1? Maybe yes, but maybe values were in UTF-8 before putting them in!? Try to convert your DB values in iso-8859-1 when outputting to you aspx pages to see if it helps.. You have to find the step where the encoding breaks and it could be somewhere else before your MVC action parameters.
Mike Gleason jr Couturier
Also, I run a french/english site so I have lots of latin characters. I prefer using UTF-8 anyway to cover a broader range of characters.
Mike Gleason jr Couturier
My db is in iso-8859-1 format. But as you can see in my Index.aspx file, the string is correctly url encoded so it doesn't matter anymore if my file or db is saved in iso-8859-1. It seems that the problem is when the framework decodes it.
wmasm
A: 

I found the problem and the workaround: the value I receive is UTF-8, but if I try to use System.Text.Encoding.UTF8.GetBytes(name) it converts the characters "é" to UTF-8 values instead of "É".

The workaround is to copy the string to a byte[] and then use System.Text.Encoding.Convert().

I don't know if this is the best way, but now everything is working for me.

wmasm
+1  A: 
    public static string ActionLinkNoEncode(this HtmlHelper htmlHelper, string linkText, ActionResult action )
    {

        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);   
        var url = Uri.UnescapeDataString(urlHelper.Action(action)).ToLowerInvariant();  
        var linkTagBuilder = new TagBuilder("a");   
        linkTagBuilder.MergeAttribute("href", url);
        linkTagBuilder.InnerHtml = linkText;
        return linkTagBuilder.ToString();

    }
Wichai Damalee