Is it better to use embedded javascript or a separate .js file in an MVC3 view?

I was told that it is best to put the Javascript code in a separate file to separate the problems, and although the idea resonates with me, I do not find it practical.

It may just be my inexperience, so this is the question.

Here is an example of a clear example where I found that placing code in a view is better than placing it in a separate javascript file.

In my view, I needed to invoke the JQueryUI dialog box and set the title dynamically with the name of my model.

$("#thumbs img").click(function () { var url = $(this).attr("src"); $(".image-popup").attr("src", url); return $("#image-popup").dialog({ modal: true, closeOnEscape: true, minHeight: 384, minWidth: 596, resizable: false, show: { effect: 'slide', duration: 500, direction: 'up' }, hide: { effect: 'slide', duration: 250, direction: 'up' }, title: '@Model.Product.Name' }); }); 

Note:

 title: '@Model.Product.Name' 

As you can see, I have access to a strongly typed model if I use Javascript in my view. This is not the case if I use a separate Javascript file.

I am doing it wrong, is there something that I do not see?

If I were to use a separate file, how would it look like a view, since I cannot access the model properties from a Javascript file?

+9
javascript c # asp.net-mvc-3
Apr 05 2018-12-12T00:
source share
2 answers

Separate js file:

 <div id="thumbs"> <img data-dialog-title="@Model.Product.Name" src="[whatever url]" /> </div? $("#thumbs img").click(function () { var title = $(this).data('dialog-title'); var url = $(this).attr("src"); $(".image-popup").attr("src", url); return $("#image-popup").dialog({ modal: true, closeOnEscape: true, minHeight: 384, minWidth: 596, resizable: false, show: { effect: 'slide', duration: 500, direction: 'up' }, hide: { effect: 'slide', duration: 250, direction: 'up' }, title: title }); }); 

Access to model properties is unobtrusive via dom using data5 * HTML5 attributes. The javascript above will work just fine as an external file.

+12
Apr 05 2018-12-12T00:
source share

If you can't use the above HTML5 data attributes, perhaps http://nuget.org/packages/RazorJS will do the trick, it looks like it might solve your problem.

0
Apr 6 2018-12-12T00:
source share



All Articles