2

I am trying to assign HTML to TempData as such:

     TempData["FilesUploaded"] = "<option value= '" +  file.FileName + "'>" + file.FileName + "</option>";

I need to get this value in Jquery. As such, I do the following:

    var val = '@TempData["FilesUploaded"]';

    alert(val);

What I am finding is that the characters are coming as such:

    &lt;option value= &#39;PS Report #36178.pdf&#39;&gt;PS Report #36178.pdf&lt;/option&gt;

I tried to do it enclose TempData in @Html.Raw(... but that did not work as well.

Here is what I tried:

    var val = '@Html.Raw((string)TempData["FilesUploaded"])';
    alert(val);

What is odd is that it doesn't work in that the alert doesn't even come up.

1
  • Now I read the last line. Can you post your version using Html.Raw? Commented Jan 31, 2013 at 21:11

1 Answer 1

11

Use HttpUtility.JavaScriptStringEncode to encode the string as JavaScript:

var val = '@Html.Raw(HttpUtility.JavaScriptStringEncode((string)TempData["FilesUploaded"]))';
Sign up to request clarification or add additional context in comments.

1 Comment

@NatePat OK now I realized the problem. Html.Raw outputted the single quotes, which made the script invalid. The single quotes have to be replaced with \' in order for the output to be valid js

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.