Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I have a property in Model

public CodeString {get; set;}

which contains string value something like this

<SCRIPT src="http://demo.com/add/091221"> </script><SCRIPT src="http://demo.com/add"> </script>

i want to add CodeString property's value to the body section of the view.I am seeing CodeString Value in assigning it to hidden field and alerting the hidden field. But script is not getting added to the head section. I am trying to using this hidden field as follows:

     $(document).ready(function () {
         $('head').append($("#PixelCodeString").val());
});

Still not seeing the script tag in the generated html page. Folks what's going wrong in this? any ideas?

share|improve this question
    
jsfiddle.net/Spokey/3Ubqv - seems to be working fine, do you get any errors in your console? – Spokey May 27 '13 at 13:45

4 Answers 4

If you just view the source, then you will not see that part since it is added through client code.. (view source will only show what was sent from the server)

You can use firebug to see the live DOM and you will find it..

A simple test with

<input id="code" value="<script>alert('test');</script>"/>

and

$('head').append( $('#code').val() );

is working fine at http://jsfiddle.net/gaby/57AgH/

share|improve this answer

One question: are you putting the raw value there to avoid escaping the <?

Anyway, you should not need to put the code in an hidden field and you don't have to put the scripts in the <head> tag: you can simply output the content of the property. For example if you are using Razor:

@Html.Raw(Model.CodeString)

On a side note, if I were you I would use getScript() from jQuery. That way I can load all my scripts later. To do that you will need to change your property to a List<> of script Urls and use getScript for each one.

share|improve this answer
    
Perfect... Tallmaris... I was digging around all the jquery stuff to do this but it was really so easy to do so.. Thanks a lot... :) – kaustubh shukla May 27 '13 at 14:04

on your cs page

public CodeString {get; set;}
string script="</script>$(document).ready(function () {
         $('head').append($("#CodeString").val()); </script>"

});
Page.ClientScript.RegisterStartupScript(typeof(Page), "Your script", script);
share|improve this answer
<script type="text/javascript">
$(document).ready(function(){
        var myCar='@ViewBag.Car'; // Here i am trying to access the ViewBag here
        $("#myCarDiv").html(myCar);
});
</script>
<div id="myCarDiv"></div>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.