asfsadf
asfsadf

Reputation: 3862

JavaScript parameters coming from view's model data

I've seen/read plenty advocating "unobtrusive" JavaScript contained in separate files. I'm preparing to combine all my JavaScript from three partial views into a single file that I will then reference somewhere in my master.

My question is: is there any type of JavaScript that should remain behind in the html? One example that seems to me may present a problem would be something like:

<script type="text/javascript">
    $(document).ready(function () {
        $('#newQuoteLink').click(function () {
            $('#newQuoteLink').hide();
            $('#newQuoteDiv').load('/Quote/Create/<%:Model.Book.BookID%>');
            return false;
        });
    });
</script>

--in particular the

<%:Model.Book.BookID%>

Am I correct in assuming this script would not work if loaded from a separate file?

I mostly wanted to check if there were any caveats or other considerations prior to combining everything into this lone, separate file.

Thanks in advance.

Upvotes: 2

Views: 244

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038840

Nope, promise to never ever hardcode url addresses that are route dependent like you did in your javascript file. It's bad, bad, bad. Did I say it's bad?

That's too much of a javascript in a view (it's a bandwidth waste). You could try a global javascript variable declaration your view:

<script type="text/javascript">
    var quoteUrl = '<%: Url.Action("create", "quote", new { id = Model.Book.BookID }) %>';
</script>

and in your javascript file:

$(function () {
    $('#newQuoteLink').click(function () {
        $('#newQuoteLink').hide();
        $('#newQuoteDiv').load(quoteUrl);
        return false;
    });
});

That's a path I wouldn't personally take. Still a script tag with a global javascript variable declaration in your view. Still a waste.


Things become even prettier like this (and it is at that moment that you realize the real power of unobtrusive javascript):

<%: Html.ActionLink("Foo Bar Beer Link Text", "create", "quote", 
    new { id = Model.Book.BookID }, new { id = "newQuoteLink" }) %>

and in your external javascript:

$(function () {
    $('#newQuoteLink').click(function () {
        $('#newQuoteLink').hide();
        $('#newQuoteDiv').load(this.href);
        return false;
    });
});

Upvotes: 3

Java Drinker
Java Drinker

Reputation: 3167

Yep, you're right in that <%:Model.Book.BookID%> will not be visible to the script file. These things are part of the server side script that generates the HTML that is sent to the browser.

You can put all the bulk of the work in the script in a funciton which accepts the id as a param, and then in your html, from your .ready(..) call the function like doStuff("<%:Model.Book.BookID%>") etc.

Javascript experts: other caveats? I'll update when i think of some

Upvotes: 1

Related Questions