4

I need to call a jquery function on the view, using server side variable, the variable are set in the viewbag without encoding the variables values.

eg.:

ViewBag.innerTitle = "<div id='title45'>My Title</div>"; //C#

$(function(){ alert(ViewBag.Title) }); // Js can I Access it
2
  • what are the templates engine razor or regular aspnet view ? Commented Aug 9, 2012 at 12:36
  • What do you expect as the output of that? Note in particular that .innerTitle and .Title are different - is that intentional? or a typo? Commented Aug 9, 2012 at 12:41

2 Answers 2

4

Personally, with that type of content I would be writing the html to the page, and just using jQuery, i.e.

alert($('#title45').text());

Then the js is fixed, ideal for use on a static .js file that is downloaded and cached separately.

If you must write it to dynamic js:

alert('@Html.Raw(HttpUtility.JavaScriptStringEncode(ViewBag.Title))');

but I would be nervous about single and double quotes.

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

3 Comments

Icant use it before sending the markup to the dom , since the html currently are stored in the viewbag ?
@JhonyHana can you rephrase that? it is hard to understand what you mean, not least because you haven't actually shown us an example of what ViewBag.Title contains, or what you expect the displayed text to be.
@MarcGravell Am I correct JavaScriptStringEncode is always to be paired with Html.Raw when generating dynamic js?
0

if your are using razor:

simply in your js:

<script>$(function(){ alert(' @Html.Raw(ViewBag.Title) ') });</script>

@Html.Raw : output the markup w/o encoding it.

Comments

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.