开发者

ASP.NET: Is it possible to create dynamically-named Javascript functions without using .NET code (ie, VB.NET or C#)?

I have a custom user control (ascx) that contains a textbox and a Javascript-based counter to let the user know many characters they have left to type. In this control is the following:

function GetTextBox() {
    return document.getElementById("<%=txNotes.ClientID %>");
}

This worked fine when we only had one instance of this user control on the page, but now we have to support multiple. As you know, having multiple instances of this control on a page will result in multiple GetTextBox() functions, only the last of which will be called no matter what. To support multiple instances, I use this:

if (!string.IsNullOrEmpty(TextBoxName) && !Page.ClientScript.IsClientScriptBlockRegistered(TextBoxName))
{
    string Script = string.Format("function Get{0}Notes() {{ return document.getElementById(\"{1}\"); }}", 
        TextBoxName, txNotes.ClientID);

    Page.ClientScript.RegisterClientScriptBlock(GetType(), TextBoxName, Script, true);
}

TextBoxName is a public usercontrol property, so if the developer passes Employee through, it will generate a Javascript function called GetEmployeeNotes(). This works greate because now we can have a unique GetNotes() function.

However, I don't like how it's hardcoded into the codebehind. I would like a markup-based solution for this, something that doesn't require a rebuild of the project in case I want to change the Javascript. Does anyone know of a way to do this?

Edit: I've already thought of creating a separate .js file that I could read with a text reader, but that sounds a bit hacky and I'd like to avoid that if at all possible.

Edit 2: Guard's answer below would work, but I don't want to go that route for the 开发者_开发问答reason I gave beneath his answer. If no one can offer another way to do what I want to do, I will most likely mark his as the answer since it technically does exactly what I am asking.


I'm not a .NET specialist, but isn't it working as a preprocessor?

Isn't it legal to write

function Get<%=Name %>Notes() {...}

?


Why not use a generic function and just pass the id of the corresponding textbox? As in: GetNotes(thisTextBoxId) {...}. Not only would that deal with your problem but also is more DRY.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜