• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 529
  • Last Modified:

Dynamic JavaScript with ASP.NET MVC

I have some javascript that I want added to one of my Views, but only after certain things are passed through a post. In WebForms I would have used Page.ClientScript.RegisterClientScriptBlock, but I am not sure how to do this with MVC.
0
UCTechs
Asked:
UCTechs
  • 2
  • 2
1 Solution
 
jamesbaileCommented:
just add a script tag to your view

<script type="text/javascript" src="myscriptfile.js" ></script>

0
 
UCTechsAuthor Commented:
I need the script to be added dynamically to the view as the script will be different based on the posted information. The method you suggested is just a static entry on the view and gives me no control of the rendered script.
0
 
jamesbaileCommented:
What about something like this in your view?

<% if (Model.MyProperty == "abc") { %>
   <script type="text/javascript" src="myscriptfile.js" ></script>
<% } else { %>
   <script type="text/javascript" src="AdifferentScriptfile.js" ></script>
<% } %>

Alternatively you can put things in from your model if you embed the script into your view

<script type="text/javascript" >
   var avalue = '<%= Model.AProperty %>';
</script>

Personally I try and keep javascript out of my views and only include an initialisation function which passess in the values I need from the model.

Therfore I'd do something like this in my view

<script type="text/javascript" src="myscriptfile.js" ></script>
<script type="text/javascript" >
    initialiseSomething('<%= Model.MyProperty %>','<%= Model.AnotherProperty %>');
 </script>




0
 
UCTechsAuthor Commented:
That is a good idea. Not as ideal as sending it directly down from the controller, but in this instance it should work just fine. I appreciate your help. Thanks!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now