Justin
Justin

Reputation: 6559

Best way to write javascript to ASP.NET

My scenerio is a user could click on 12 different items on the page and depending on which item they click, a div will be populated with text. I was thinking a good way to do this is just pass all the different text strings to the client on their first request rather than doing a possible of 12 different AJAX calls. I figured front loading the client with the initial load time would be better since the text strings aren't long anyways.

What I am trying to figure out is the best way to write a javascript dictionary/hastable in my C# code behind and pass it to the page on load. What would be the best way to do this?

Upvotes: 1

Views: 2305

Answers (6)

RichardTowers
RichardTowers

Reputation: 4762

From the point of view of the client you've basically got two choices:

  1. Trigger an AJAX call on page load to get the data asynchronously. (See Sjoerd's answer)
  2. Get ASP to push the data directly into your HTML / JavaScript. (See Ewerton / Scorpio's answers)

If you're uncomfortable having ASP generate your JS dynamically you could also get it to output a script tag with your data in it:

<script type="text/json" id="strings">
     <asp:Literal runat="server" ID="JavascriptData" />
</script>

Produces:

 <script type="text/json" id="strings">
     { "div1" : "First String",
       "div2" : "Second String",
       "etc" : "And so on" }
 </script>

And then read the data in your javascript:

var json = document.getElementById('strings').InnerHTML;
var strings = JSON.Parse(json);

Upvotes: 1

SutharMonil
SutharMonil

Reputation: 88

You can store your html content in a string format in hidden fields, or you can populate 12 separate divs from your server side code. Then write some javascript to show-hide divs based on the button clicks.

Upvotes: 0

Scorpio
Scorpio

Reputation: 1171

protected void btnHey_Click(object sender, EventArgs e)
{
 StringBuilder sb = new StringBuilder();

 sb.Append("<script language='javascript'>alert('HEY');</script>");

 // if the script is not already registered

 if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "HeyPopup"))

      ClientScript.RegisterClientScriptBlock(Page.GetType(), "HeyPopup", sb.ToString());
}

You can take a look at this http://www.dreamincode.net/forums/topic/185586-aspnet-calling-javascript-from-code-behind/ I hope it helps...

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272416

  • You can create 12 hidden divs, populate them with HTML and show the appropriate one depending on what the user clicked.

  • You can convert the Dictionary object to a JavaScript object literal, something like:

var pageContent = {
    button1: "some content",
    button2: "some other content"
    // ...
};

Have a look at System.Runtime.Serialization.Json Namespace and this answer for code. You can then populate a div with the content depending on button clicked.

Upvotes: 1

Sjoerd
Sjoerd

Reputation: 75679

To solve such a problem myself, I have made a HttpHandler that returns JSON:

public class JsonData : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var json = serializer.Serialize(GetData());
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }
}

In the Javascript of my ASPX I use jQuery to retrieve the data:

$.getJSON("/JsonData.ashx", null, function (data) { ... });

This is really an out-of-band solution, in that the ASPX file retrieves a second file with the data.

What I also sometimes see is something like this:

<script>
    var myData = '<asp:Literal runat="server" ID="JavascriptData" />';
</script>

Where JavascriptData is then filled in the codebehind. I don't really like this method, but it is simple and it works. Don't forget to escape your quotes.

Upvotes: 0

Ewerton
Ewerton

Reputation: 4533

ScriptManager.RegisterStartupScript will do the trick

Upvotes: 0

Related Questions