99

I want to send the variables itemId and entityModel to the ActionResult CreateNote:

public ActionResult CreateNote(
        [ModelBinder(typeof(Models.JsonModelBinder))]
        NoteModel Model, string cmd, long? itemId, string modelEntity)

with this javascript:

Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});

However, the url being send is

localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44     

I want to send

localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44

How can I prevent Url.Action to put the & in front of the second variable that I want to send?

Niek de Klein
  • 8,524
  • 20
  • 72
  • 143
  • What makes you think that `&` is not OK? – Oded Jan 03 '12 at 11:28
  • 1
    Because when I look at the ActionResult with a breakpoint, when I have localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44 modelEntity = Phrase and itemId = null. When I turn them around in javascript and get localhost:1304/Administration/blue/en-gb/Entity/CreateNote?itemId=44&modelEntity=Phrase itemId = 44 and modelEntity = null. That's why I think it has to do with the & – Niek de Klein Jan 03 '12 at 11:36
  • 4
    @Oded — because the data is being inserted into JavaScript, not HTML. – Quentin Jan 03 '12 at 12:08

2 Answers2

141

I didn't notice yesterday that you had & I thought that was the SO editor had changed that. Try wrapping your Url.Action() in a @Html.Raw() to prevent the Encode of &.

Or alternatively only Url.Action() the controller/action bit and pass the two parameters as post data rather than directly on the url, jQuery should sort out the &'s for you that way.

K. Bob
  • 2,668
  • 1
  • 18
  • 16
  • 48
    This solution works, but why does Url.Action even get encoded? Talk about unexpected behavior. – Jerry Apr 19 '12 at 22:25
14

I think your problem is with Model.meta.PostAction - is that property a string?

If so then my guess would be that you're adding it to the page with either:

  • Razor: @Model.meta.PostAction
  • ASP view engine: <%:Model.meta.PostAction%>

Both of which automatically encode that string for you.

To fix it either use @Html.Raw()/<%= (both of which don't encode) or make the PostAction property an IHtmlString that knows that it's already been encoded:

string actionUrl = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
Model.meta.PostAction = new HtmlString(actionUrl);
Keith
  • 150,284
  • 78
  • 298
  • 434