dotnetnoob
dotnetnoob

Reputation: 11360

How do I pass data from c# to jquery/javascript?

I have a function that I'd like to run when the page loads, so either in document.ready or pageLoad.

Using jquery, I'll trigger the function using its class name

In document.ready

var span = $('.linkify');
span.html(textToLinks(span.html()));

Elsewhere

function textToLinks(text) {

    var exp = /(my text)/ig;
    return text.replace(exp, "<a class='link' href='http://www.bbc.co.uk' target='_blank' >$1</a>");

}

Now this works with the simple test data, but I need to now work out how to expand the functionality.

I have a list of terms in my c# app, along with the relevant url. I'm thinking of passing this data as a string, and splitting in, however my javascript knowledge has a lot of holes.

So I suppose I have 3 questions:

  1. How do I get my string into the function when the page is loaded?
  2. Is a string the right type or can I pass some other dictionary object?
  3. How do I iterate through each of the terms passed efficiently?

Thanks in advance.

Upvotes: 0

Views: 11554

Answers (5)

cdie
cdie

Reputation: 4544

You can do this way :

Declare public member into your C# class on code behind

public string mystring;

Initiate it in Init or Load Event And write that on your js function

var exp = '<%=mystring %>';

It should work for string. For Dictionnary, you may try to do Ajax

Upvotes: 1

Nunners
Nunners

Reputation: 3047

Another possible way of doing this is to write the javascript function at page load in your C# code. This will then be added to the page when it is rendered and can be executed by the jQuery on document.ready(); or any other function / event.

Example code :

    string FunctionStr = "<script type=\"text\javascript\">function textToLinks(text) {" +
        "var exp = /(my text)/ig;" +
        "return text.replace(exp, \"<a class='link' href='http://www.bbc.co.uk' target='_blank' >$1</a>\");" +
        "}</script>";

    this.ClientScript.RegisterClientScriptBlock(this.GetType(), "Some JS Function", FunctionStr);

The answers from Anand and Daniel may better suit your desired approach but this is a 3rd option if you desire one.

Upvotes: 1

Anand
Anand

Reputation: 14955

What you can do is, use JQuery Ajax call to retrieve server side data.

But that would require you to set up service that would be exposed. You could do it in a shortcut way with out setting up the service.

But that would require messy logic.(its a short cut :))

You could create a property in your page which exposes the JSON Data as string. You could read the JSON data in your javascript by following

var data =<% GetData() %>

You can define a ToJson on object to convert the object in to JSON String

    public static string ToJSON(this object obj)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer(new SimpleTypeResolver());
        return serializer.Serialize(obj);
    }

public string GetData()
{
    return (new {SomeData}).ToJson();
}

Note SomeData is a class containing your data(i.e array of urls) or what ever representation you choose.

Then loop over data to build the dynamic html

Upvotes: 2

Joe Enos
Joe Enos

Reputation: 40431

If you've got your data in advance when the page is loaded, you can write the JSON directly to the page, then use that javascript object to do whatever you need.

I don't know if you're using MVC or WebForms, but the idea is basically the same:

For example (using JSON.NET to serialize):

<script id="some-data" type="application/json">
    <%= JsonConvert.SerializeObject(someDotNetObject) %>
</script>

<script type="text/javascript">
    var _someJsObject = JSON.parse(document.getElementById("some-data").innerHTML);
</script>

Now _someJsObject is a javascript object representing the data you started with, and you can do whatever you want with it, like looping through an array, etc.

Side note - if you're targeting IE7, you'll need to use something like json2.js to get the JSON parsing.

Upvotes: 1

Vivian River
Vivian River

Reputation: 32410

@Anand is correct saying that you can use jQuery Ajax to retrieve server-side data.

However, depending on exactly what it is you want to do, you might be able to do it another way.

You can use the .net JavascriptSerializer class to serialize your data to JSON format. JSON is a very good tool to become familiar with if you aren't already familiar with it.

JavascriptSerializer will put your JSON in a string, which you can then put inside a hidden input and read with your Javascript code. This has the advantage that there is no need for a second HTTP request, as would be the case with jQuery Ajax.

Upvotes: 1

Related Questions