How to hook up jQuery + MVC View User Control / MVC View ?

Rate It (1)

Last post 02-24-2008 3:10 PM by abombss. 29 replies.

Sort Posts:

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-21-2008, 8:49 PM
    • Loading...
    • katokay
    • Joined on 12-03-2006, 4:37 PM
    • Posts 50

    You're completely right about not mentioning anything about not having script tags in your document. That's what I was trying to express by saying "loose definition". However, taking a look at samples from the jQuery in Action book, or anywhere else in the book itself I can't find a single example where they use jQuery javascript in the body of the document. I interpreted that as separating behavior from content. CSS was designed with the same goal in mind separating style from content. Can you still include style tags in content with CSS? Sure, I think there's plenty of room for interpretation and to each their own. I was only expressing mine.

    http://www.manning-source.com/books/bibeault/jqia.source.zip 

    Inside Site.Master 

    <head runat="server">
        <title>My Sample MVC Application</title>
        <link href="../../Content/Site.css" rel="stylesheet" type="text/css"  />
        <asp:ContentPlaceHolder ID="HtmlHeader" runat="server">
        </asp:ContentPlaceHolder>
    </head>

     Inside content page

     <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="MvcApplication.Views.Home.About" %>

    <asp:Content ID="Header" ContentPlaceHolderID="HtmlHeader" runat="server">
        <script type="text/javascript" language="javascript" src="scripts/jquery.js"></script>
        <script type="text/javascript" language="javascript">
            $("#form").filter("[name=sometext]").doSomething();
            $("some other selector").doSomethingElse();
            $("some other selector").click(function(){
                //do something here
            }).doSomethingMore();
        </script>
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">

        <div>page content here</div>
        
    </asp:Content>

     

     

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-21-2008, 11:02 PM
    • Loading...
    • pure.krome
    • Joined on 05-28-2006, 4:45 AM
    • Melbourne, Australia
    • Posts 258

    Katokay, that's an interesting way to look at it. I see what u mean, now.

    As i use lots of View User Controls, this means that the View User Control i wish to use doesn't need to be bound to any logic -- in this case binding some click event .. say. At the same time, you might look at your View User Control and say, i always want this control to be bind some javascript. hmmm.

     Ok .. lets have another look at Katokay's idea. So if we have some MainContentPlaceHolder and inside that we have some View User Control. We have no idea what controls are inside that View User Control .. we just know what it's suppose to show (eg. A single northwind product). Is it good or bad that the current view (ie. Content Page) needs to know what to bind inside this View User Control? Should the content page need to know this information? or by having the View User Control only worry about itself, then any consumers of the View User Control don't need to worry about what happens inside it?

    arg :( what to do!

    thoughts Katokay and tgmdbm?

    :: Never underestimate the predictability of stupidity ::
  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-21-2008, 11:04 PM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 682
    • ASPInsiders

    I agree katokay.

    But you still have the problem of how to register the scripts that a Control requires and still have a good reusability story. Even when using Html.RenderUserControl().

    Using inline <script> tags is the easiest option.

    At the moment, however, I can't see a solution to this because at the time that you call Html.RenderUserControl(), the <head> has already been rendered, and the Controls are rendered out of context (in a dummy page).

    If anyone can think of a solution I'm all ears. 

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-22-2008, 12:52 AM
    • Loading...
    • katokay
    • Joined on 12-03-2006, 4:37 PM
    • Posts 50

     I think there's a good balance in there somewhere. I can't see anything but ugly options, if any to programatically hook in and register the script on the page that consumes the control. To play devils advocate I would argue that behavior can be page specific and not control. Would that be true always, of course not. Making a control for re-use doesn't necessarily mean you have to bottle the ajax behavior with it as one example. One page may have just login functionality no ajax, another may have an animated call out and login via an ajax post. Either way there never seems to be a one size fits all for these things. Funny thing, I almost added one line to my last comment thinking "You're going to throw the user control argument at me next". It seems like it would be a nice hook to have from a user control, to be able to register a script that shows up in the head section.

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-22-2008, 4:15 AM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 682
    • ASPInsiders

    katokay:
    I would argue that behavior can be page specific and not control

    Agreed.

    katokay:
    It seems like it would be a nice hook to have from a user control, to be able to register a script that shows up in the head section.

    Yeah, this is what i just can't imagine implementing without capturing output and doing some post processing. It shouldn't be too difficult to register scripts but they would need to be output at the end of the page (or the master).

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-22-2008, 8:04 AM
    • Loading...
    • katokay
    • Joined on 12-03-2006, 4:37 PM
    • Posts 50

     I suppose there's a good jQuery script to move them into the head tags Stick out tongue

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-22-2008, 8:30 AM

    katokay:
    Putting a ContentPlaceHolder on the master page, and using it when needed in content pages as mentioned earlier, IMHO would be the best option.

    Yes, certainly for core initialisers for the page, having it in the Head. But a benefit of having inline script blocks following each Control is that if this is a fragment of HTML returned via AJAX, most new AJAX libraries call eval() and will evaluate the new inline script. So this makes it a quick way to initialise controls when UpdatePanel style partial page updates are being done. Again, a more robust way may be to have listeners to bind events when new HTML is injected. And have this code more globally on the page. But for rapid development this is a handy approach.

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-22-2008, 9:15 AM
    • Loading...
    • katokay
    • Joined on 12-03-2006, 4:37 PM
    • Posts 50

     That's a good point. I would also recommend taking a look at the jQuery plugin Live Query to achieve similar results if the shoe fits.

    http://plugins.jquery.com/project/livequery  

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-22-2008, 11:12 AM

    katokay:
    jQuery plugin Live Query

    That's a pretty cool plugin. Very useful for auto-magic binding of appended HTML. Thanks for the link.

    So that's one more library to add to my essential toolkit for Microsoft MVC projects:

     

     

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-22-2008, 9:38 PM
    • Loading...
    • pure.krome
    • Joined on 05-28-2006, 4:45 AM
    • Melbourne, Australia
    • Posts 258

    An interesting point a few of you guys are constantly bringing up is the requirement to place the javascript in the HEAD element. I think i even raised this point. But alas, this i think is wrong.

     The guys at Yahoo have a great post (about a book they made) regarding website optimisations and that the javascript should be added at the end.

    here's the post / info:

    - Summary info: http://developer.yahoo.com/yslow/
    - Specific Rules: http://developer.yahoo.com/performance/index.html#rules
    - Javascript rules, saying JS should be placed at the END of the document : http://developer.yahoo.com/performance/rules.html#js_bottom

    :: Never underestimate the predictability of stupidity ::
  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-23-2008, 12:19 AM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 682
    • ASPInsiders

    Thanks p.k,

    I knew about the benefits of putting scripts at the end of the body, I didn't know it's xhtml compliant. 

    I'm happy now,

    http://www.w3.org/TR/2003/WD-xhtml2-20030506/mod-scripting.html#edef_scripting_script

     

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-23-2008, 11:22 AM
    • Loading...
    • katokay
    • Joined on 12-03-2006, 4:37 PM
    • Posts 50

    Interesting reads. Thanks for the tips. Another interesting discussion about this subject.

    http://groups.google.com/group/jquery-en/browse_thread/thread/8570c3a4347c6592/4418e9c7360e245f

    So going back to the user control issue. In this instance you would need to make sure the jquery.js file is loaded before your user control (assuming you chose to put script tags in the control) otherwise you'll have issues. Which may seem obvious to some, but still a good thing to remember.

     

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-24-2008, 12:07 AM
    • Loading...
    • tgmdbm
    • Joined on 12-17-2007, 2:08 PM
    • Posts 682
    • ASPInsiders

    Here's an idea that needs a little fleshing out.

    I was trying to think about how to include a control with and without scripts, depending on whether the page wanted the ajaxified version of the control or not...

    Define 2 standard content place holders in all your controls, one for the presentation and another for your scripts, for example...


    <asp:Content ID="Content1" ContentPlaceHolderID="PresentationPlaceHolder" runat="server">
    <!-- Html goes here -->
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ScriptPlaceHolder" runat="server">
    <script type="text/javascript" src="myscript.js"></script>
    <script type="text/javascript">
    // script goes here
    </script>
    </asp:Content>

    Then define 2 master pages, one with the two place holders called WithScript.master...

    <asp:ContentPlaceHolder ID="PresentationPlaceHolder" runat="server">
    </asp:ContentPlaceHolder>
    <asp:ContentPlaceHolder ID="ScriptPlaceHolder" runat="server">
    </asp:ContentPlaceHolder>
     ... and one with just the presentation called WithoutScript.master...
    <asp:ContentPlaceHolder ID="PresentationPlaceHolder" runat="server">
    </asp:ContentPlaceHolder>

    Then when you call RenderView( "MyControl", "WithScript", viewData ); you'll get both the presentation and the script. And if you use "WithoutScript" you'll just get the html.

    This won't work as it stands because you'll get Cannot find ContentPlaceHolder 'ScriptPlaceHolder' in the master page '...\WithoutScript.master'.

    Of course you could easily write a simple NullContentPlaceHolder which would simply black hole the scripts. But, better yet, you could write a type of ContentPlaceHolder which would save the output of all such place holders in an object which you could access from the Site.master. so as you are rendering controls, the scripts are getting dumped into a StringBuilder which you can output at the end of the page...

    You could also do some duplication removal...?

    Like i said this needs fleshing out...

    Maybe there's something the framework could do to help us out? does RoR have good script/control separation // control reusability story?
     

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-24-2008, 6:17 AM

    Surely normally it's up to the View not the MasterPage (or Controller) as to which scripts to include in a finer grained way?

    <asp:Content ID="Content1" ContentPlaceHolderID="PresentationPlaceHolder" runat="server">
     <!-- Html goes here -->
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ScriptPlaceHolder" runat="server"> 
      <% if ((bool)HttpContext.Current.Profile["enableAjax"]) { %>
      <script type="text/javascript" src="myscript.js"></script> 
      <script type="text/javascript">   
      // script goes here 
      </script>
      <% } %>
    </asp:Content>

    And are there other ways to build into the development process checks for required scripts or to toggle between compressed and debug versions of javascript? This saves having to come up with generic RegisterScripts or ContentPlaceHolder conventions.

    <% if (System.Diagnostics.Debugger.IsAttached) { %>
      <script>
      checkForRequiredJavascriptFilesOrFunctionsAndAlert('jquery', '1.2', 'Make sure jquery library included in the head of your master page or view.');
      </script>
    <% } %>

    The other point to consider is the number of levels of UI and javascript that are required - it may not just be javascript on or javascript off via the master page - so finer grained If blocks in the View again come in handy. There may be versions for rich clients (IE and Firefox), reduced javascript for mobile clients, reduced javascript for screen readers (they can still run javascript, just best to stick to simple things like form validation, with proper accessible alerts), no javascript. With a whole mix of <noscript> regions and conditions within the javascript files themselves too.

    I suppose it will be some of the emerging bigger MVC sample apps such as Code Camp Server that might help identify some of the best practice. And as you say, I've been looking at the source code of RoR apps to get some ideas! (Many RoR sample apps do tend to be simpler and less developed than I'd thought!?!)

  • Re: How to hook up jQuery + MVC View User Control / MVC View ?

    02-24-2008, 3:10 PM