views:

231

answers:

3

I have a javascript function that I need to call inside my body tags. My javascript fuction looks like this:

function NewExistingPicture(pictureName) {

    //code for javascript function
}

And this is what I'm trying to do in HTML:

Existing Photos:
<% foreach (var Photo in Model.ProductThumbnails) 
   { %>
      NewExistingPicture(<%= Html.Encode(Photo.PhotoName) %>) 
<% } %>

Obviously this isn't going to work, but I'm at a loss as to how to pass the function the information from the model.

A: 

I think you'll need to do something like writting out a complete script section with all the javascript in it which is then run when the document has completed loading.

I think this might also be best written out from the controller code so you can set a variable and then insert that into the page.

<%= Model.Javascript %>

and in the controller;

ActionResult MyAction()
{
  myModel.Javascript = "<script>alert(9);</script";
  return View(myModel);
}

The above is completely untested but should work anyway me thinks.

griegs
You would need to create a Javascript property on the Model. For the sake of example, you may be better off using ViewData.
JoshJordan
Agreed but I'm just not a big fan of ViewData.
griegs
+2  A: 

Try this:

<script type="text/javascript">
<% foreach (var Photo in Model.ProductThumbnails) 
   { %>
      NewExistingPicture('<%= Photo.PhotoName.Replace(@"'", @"\'") %>'); 
<% } %>
</script>

(the .Replace() is to escape any single quotes in your string, so the string you're creating will be valid)

kevingessner
Oh cool, I wasn't aware that the <% tags would get picked up
ajbeaven
Assuming users have any control at all over photo names, this is not safe (XSS).
nullptr
Where's the XSS vulnerability? The .Replace guarantees that the entire photo name will be within the JS string, even evil input like "');alert('hacked');alert('".
kevingessner
Does doing <% Htlm.Encode(//stuff here) %> do the same?
ajbeaven
A: 
<%@ Import Namespace="System.Web.Script.Serialization" %>
<% var js = new JavaScriptSerializer(); %>
...
NewExistingPicture(<%= Html.Encode(js.Serialize(Photo.PhotoName)) %>)
nullptr