How to dynamically add a row to an html table (with server data) on a dropdown cell in asp.net mvc
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 n开发者_Python百科ow 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:
- 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?
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"});
}
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!
精彩评论