The Sheek Geek
The Sheek Geek

Reputation: 4216

MVC3 html helpers and javascript

I have an html helper in MVC3 that renders a custom section of html that is being used as a search control. The issue is that there is javascript (jquery) that has been written to interact with the control (it really should be used JUST for this control). Is there a way to make the javascript embedded so that the control continues to have the javascript functionality. (With creating the helper, we can control how the html is structured and make it easier to write the javascript. This would standardize the use of the control across out app).

ex.

<div>
@Html.SearchControl("searchControlSelector")
</div>

<script>
     $("searchControlSelector").timeout();
<script>

I want to be able to set the 'timeout' functionality when calling the @Html.SearchControl([some params]) so that the javascript and helper are combined and users of the helper do not have to worry about what selectors they should use when calling 'timeout'. Does anyone know how to achieve this? Is there a better way of handling this?

Upvotes: 3

Views: 4523

Answers (2)

STO
STO

Reputation: 10638

It is hard to make completely reusable html helper with single shared javascript file.

At first it is not possible to output only one <script>$(".searchControl").timeout()</script> code block per page without using additional method calls in layout page etc.

You could add your own control-specific data-attribute like data-search-control and use it in selectors like $("input[data-search-control]").timeout() to distinct only HTML produced by your helper.

If it is ok for you to have multiple scripts block on page don't forget they will be executed few times so you need to care about preventing multiple execution. You may associate some data with HTML nodes already processed by the script using for example jQuery $("").data() method. Or as option you may check if specified object in global scope is declared and if it is then do nothing otherwise declare it and call your method.

Upvotes: 1

davehale23
davehale23

Reputation: 4372

When I want to do something like this, I tend to keep it as simple as possible. Here is some code that sounds like it would fit the bill.

using System;
using System.Text;
namespace MvcApplication1.Helpers
{
    public class Html
    {
        public static string SearchControl(string selector)
        {
            StringBuilder returnString = new StringBuilder();
            //put your existing code here.
            returnString.Append(String.Format("<label >{0}</label>", selector));
            //just add the JS as string, (wrapped in a 'ready' if you need that)
            returnString.Append(String.Format("<script>$(function(){$(\"{0}\").timeout();});<script>", selector));
            return returnString.ToString();
        }
    }
}

If this isn't helpful, please add more description to your question and we'll try to help.

Upvotes: 1

Related Questions