سؤال

I am attempting to create a ASP .Net (VB.Net) custom control for an auto-complete drop down that uses jQuery auto-complete.

The basic flow is the consumer of the control will set some properties (such as the data source) which will then be injected as javascript to initialize the autocomplete.

There are a lot of pieces involved so i may have missed posting some of the code, please comment if you think something is missing and i will add it.

the consumer's code behind (PreInit event):

myDropDown.DataCallback = "testFunc";

the DataCallback property in the control:

Public Property DataCallback As String

the options object creation and javascript injection in the control code behind (PreRender event):

Dim _serializer As New JavaScriptSerializer()
Dim optionsObject As New Dictionary(Of String, Object)
optionsObject.Add("source", DataCallback)
Dim optionsJSON = _serializer.Serialize(optionsObject)

Dim initializeScript = String.Format("initialize('{0}', {1});", ClientID, optionsJSON)
Attributes.Add("onfocusin", initializeScript)

and finally, the javascript:

var initialize = function (controlID, options) {
    if (options) {
        $('#' + controlID).autocomplete(options);
    }

    // remove the blur event handler that called this initialize function
    $('#' + controlID).removeAttr('onfocusin');
};

when i debug into the initialize function, i see options has one property, source, with the string "testFunc" as it's value. what i need is for source's value to be testFunc (not as a string) so it can be executed as a callback in autocomplete instead of autocomplete thinking it is a URL.

هل كانت مفيدة؟

المحلول

The easiest way to correct this is with a bit of pattern recognition. Your problem arises because the string property is being serialized as a string and enclosed in quotation marks. You instead want it to represent an object reference, which means getting rid of those quotes. To remove the quotation marks, there's a simple regular expression you can apply to the serialized object string:

Dim optionsJSON = _serializer.Serialize(optionsObject)
optionsJSON = Regex.Replace(optionsJSON , "(?<=""source"":)""(.+?)""", "$1")

What this will do is look for the quoted string preceded by the text "source": and capture what's inside to capture group #1. It will then replace that entire match with the inner text, effectively removing the quotes from either side of the callback function's name.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top