Saturday, August 6, 2011

Getting around pain points of using a question mark in Html.ActionLink in Razor

There are two problems one might have with this:

@Html.ActionLink(@item.Name, "Details?Id=" + @item.Id)

They are:

  1. This error appears:

    A potentially dangerous Request.Path value was detected from the client (?).

     
    ...for which the cure is to put the following in the system.web section of the Web.config:

    <httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters="" />

    <pages validateRequest="false" />

  2. The HTML comes out as:

    <a href="/Whatever/Details%3fId%3d3ab1172a-6d38-406a-a1f4-36726743226e">Foo</a>

     
    ...and you don't care for the encoding. The fix:

    @MvcHtmlString.Create(@Html.ActionLink(@item.Name, "Details?Id=" + @item.Id).ToString().Replace("%3f", "?").Replace("%3d", "="))

Yay!

While I was struggling to figure this out, I learned the following:

  1. The third parameter here is the Controller:

    @Html.ActionLink("Help Page", "Help", "Home")

  2. This is an example of creating a variable outside of a foreach loop

    @{

       var foo = "bar";

    }

    @foreach(var baz in qux)

    {

       @foo<br />

    }

  3. These are some good links:
    1. http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
    2. http://stackoverflow.com/questions/4158975/set-value-of-var-in-foreach-razor-view-engine

2 comments:

  1. I use this syntax in Razor
    @Html.ActionLink("Click Here", "RedirectLink", new { id=Model.ID })

    and it works :D
    CMIIW

    ReplyDelete
    Replies
    1. Thanks! This post is as old as can be from when I was first struggling with Razor.

      Delete