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.
UCTechsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.