Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding values from C# to DIV via JavaScript

Tags:

javascript

c#

The last module of my chat script is passing values from C# code to JavaScript and JavaScript will post values to the DIV. Before I used DataBinder but when using it directly C# code is taken by AJAX's update panel. Now, I need a set of Array values to be passed via Timer Tick function to JavaScript. How can I pass Arrays from C# to JavaScript using <%= %>. A part of my code follows.

protected void Timer1_Tick(object sender, EventArgs e)
    {
        if (MyConnection.State == System.Data.ConnectionState.Open)
        {
            MyConnection.Close();
        }
        MyConnection.Open();
        OdbcCommand cmd = new OdbcCommand("Select message from messages where name=?", MyConnection);
        cmd.Parameters.Add("@email", OdbcType.VarChar, 255).Value = "human";
        OdbcDataReader dr = cmd.ExecuteReader();
        ArrayList values = new ArrayList();
        while (dr.Read())
        {
            string messagev = dr[0].ToString();
            // What should I do here?
        }
        MyConnection.Close();
    }

I don't want values to directly to be sent to the DIV. First it must be sent to JavaScript and then it must go to DIV.

For more clarification

I need C# to retrieve data from backend and to pass that data to client side (i.e. JavaScript) from JavaScript it has to be forwarded to DIV layer.

like image 249
Mad coder. Avatar asked Dec 27 '11 11:12

Mad coder.


2 Answers

I am going to suggest the JQuery approach and get rid of the server-side timer. Using JQuery and the JQuery.Timer plugin: http://code.google.com/p/jquery-timer/ you can do this easier in my opinion and it will be nicer on the client end.

In your aspx page you have the element to display output:

<span id="status" style="display:none"></span>

and also a reference to JQuery, JQuery.Timer.js, and then your code to call the c# web method.

<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/jquery.timer.js" type="text/javascript"></script>
<script>
    $(function () {
        var timer = $.timer(getMessage, 10000);
        timer.play();
    })

    function getMessage() {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: 'message-service.asmx/getDBMessages',
            data: "{}",
            dataType: 'json',
            success: getMessageSuccess,
            error: getMessageError
        })
    }

    function getMessageError(jqXHR, textStatus, errorThrown) {
       $('#status').html(errorThrown).show();
    }

    function getMessageSuccess(data, textStatus, jqXHR) {
        $('#status').html(data.d).show();
    }
</script>

I would use a web-service for the server side db message retrieval:

[WebService(Namespace = "http://site.com/service")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class contact_service : System.Web.Services.WebService
{

    [WebMethod]
    public string getDBMessages()
    {
        try
        {
 if (MyConnection.State == System.Data.ConnectionState.Open)
        {
            MyConnection.Close();
        }
        MyConnection.Open();
        OdbcCommand cmd = new OdbcCommand("Select message from messages where name=?", MyConnection);
        cmd.Parameters.Add("@email", OdbcType.VarChar, 255).Value = "human";
        OdbcDataReader dr = cmd.ExecuteReader();
        ArrayList values = new ArrayList();
        while (dr.Read())
        {
            string messagev = dr[0].ToString();
        }
        MyConnection.Close();
return messagev;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

Hopefully this makes sense. I created a web-server (asmx) and created my server-side code to return a string. In the aspx markup I use JQuery to start a timer for 10 seconds and then an .ajax post to poll the service, retrieve the message and display it. No page refresh and much less hacky from my perspective.

like image 142
justinlabenne Avatar answered Oct 20 '22 00:10

justinlabenne


Assuming the ID of your div is div1, you can do the following

div1.Controls.Add(new LiteralControl(dr[0].ToString()) + "<br />");

That will append the Message text to your Div

like image 24
Shai Avatar answered Oct 20 '22 01:10

Shai