0

How to output ampersand & as part of query string in razor view?

Let's say we have script element and some jquery code inside view:

 $.ajax({
    url: '[?]',
    success: function (content) { $('body').append(content); },
    dataType: 'html',
    timeout: 30000

But we cannot use something like this @Url.Content("~/my/custom/url?some=1&query=2") as url because ampersand will be decorated...

2
  • Hi Maxim, I've done query strings in ASP.Net Core like this: <code> Url.Action("ControllerMethod", new { param1 = Model.value[0]. param2 = "value2" }) </code> -- This will be converted to /ControllerMethod?param1=value1&param2=value2 . Do you need to do it in JQuery for some reason or will the Html helper method work? Commented May 22, 2017 at 17:47
  • Hi... something is missing )) Commented May 22, 2017 at 17:50

2 Answers 2

2

I have got it finally... It looks a bit tricky and not better than old classic ASP.Net.. but it works:

url: '@Url.Content($"~/my/custom/url")@Html.Raw($"?some=1&query=2")'

If you need to output some custom data as parameters in query string then consider HtmlEncode to avoid XSS.

Sign up to request clarification or add additional context in comments.

Comments

1

If you can do it using Razor I've done Query strings in ASP.Net Core as like this:

@Url.Action("ControllerMethod", new { param1 = "value1". param2 = "value2" })

This will converted by ASP.Net into

/ControllerMethod?param1=value1&param2=value2

6 Comments

Unfortunately this will be converted to "param1=value1&amp;param2=value2;" and only in case if ControllerMethod route exists. So ampersand is still converted.
I might have misunderstood what you are trying to do. Would you mind please posting you Controller method and relevant View code? The @Url.Action method I posted above is that standard way to do query strings to a controller method in ASP.Net Core and the ampersand does not get encoded by default in any of my production code.
Url.Content or Url.Action decodes ampersand before output... It is not any specific case.. you code simply does not work... I need & not &amp;
My apologies on the code not working for you I don't think I understand what you are trying to do. You are trying to pass a query string to a MVC controller method yes? Could you please post your view code and controller code?
I want to avoid ampersand encoding as I wrote in my question... Look at my own answer.. I had to move query string into raw section.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.