views:

165

answers:

2

I have a dropdown cell and after clicking on an item i want to add a row to a html table. I did this using javascript: (addRowToTable is a basic javascript function)

<script type='text/javascript'>
    $(document).ready(function() {
        $('#locations').change(function() {
            if (this.selectedIndex != 0) {
                var support = new Array("True", "False");
                addRowToTable(this.value, support , "Table");
                this.remove(this.selectedIndex);
                this.selectedIndex = 0;

            }
        });
    });
 </script>

but i now realized that some of the data that i need to show in the new table row, i don't have on the client side so i need to somehow:

  1. Pass the selected value to the server (controller action) and then get back the rest of the data attributes refresh the html table (ajax) with the new value on the client side after get the full data back on the server.

Does anyone have any examples of trying to do something like this?

+1  A: 

I would use the jQuery Ajax methods http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype

<script type='text/javascript'>
    $(document).ready(function() {
        $('#locations').change(function() {
            if (this.selectedIndex != 0) {
                $.get("test", { value:this.value }, function(data){
                    addRowToTable(this.value, data , "Table");
                    this.remove(this.selectedIndex);
                    this.selectedIndex = 0;
                });
            }
        });
    });
 </script>

So this will make a HTTP GET request to /test on your server, passing a url parameter of value=whatever was selected (http://localhost/test?value=something). When the request finishes you will get a data object passed into the callback that you can use when adding your row. Take a look at the jQuery docs for more info on what you get back and how to check for it (you can check response type, success or failure etc).

Hope that helps!

John Duff
+1  A: 

You can use jquery $.ajax method to get the json serialized data:

 <script type='text/javascript'>
        $(document).ready(function() {
            $('#locations').change(function() {
                if (this.selectedIndex != 0) {
                    var support = new Array("True", "False");

                $.ajax({
                type: "POST",
                url: "/YourController/YourAction,
                dataType: "json",
                error: function(xhr, status, error) { },
                success: function(data) {

                    addRowToTable(this.value, data.This ,data.That, "Table");
                    this.remove(this.selectedIndex);
                    this.selectedIndex = 0;

                }
            });
        });
     </script>

and controller action:

public JsonResult YourAction()
        {
            //do your stuff..

            return Json(new { This="this", That="that"});
        }
Misha N.