3

I am populating a list of names that will be added to my Sql Database. In this simple case, how do I send the information to SQL server without my page being refreshed?

<script type="text/javascript">
function addNewRow() { 
    $('#displayPropertyTable tr:last').after('<tr><td style="font-size:smaller;" class="name"></td><td style="font-size:smaller;" class="address"></td></tr>');
    var $tr = $('#displayPropertyTable tr:last');
    var propertyCondition = $('#txtPropAddress').val();
    if (propertyCondition != "") {
        $tr.find('.name').text($('#txtPropName').val());
        $tr.find('.address').text($('#txtPropAddress').val());        
    }
} 
</script>
...
<table id="displayPropertyTable" width= "100%">
<tr>
     <td style="font-size:smaller;" class="name"></td>
     <td style="font-size:smaller;" class="address"></td>
</tr>
</table>
...
<table>
<tr>
     <td><b>Name</b></td>
     <td colspan="2"><input id="txtPropName" type="text" /></td>
</tr>
<tr>
     <td><b>Address</b></td>
     <td colspan="2"><input id="txtPropAddress" type="text" /></td>
</tr>
</table>
...
<button onclick="addNewRow();">Add</button>
1
  • Ajax: ASP.NET MVC has great support for server-side services that can easily be called from client-side JavaScript (e.g. through JQuery). Commented Apr 27, 2010 at 20:08

3 Answers 3

2

Using AJAX via JQuery's getJSON() is a method I use a lot. getJSON() is a wrapper for the ajax() method I believe.

Here's an example of JS Method that serializes the form data and does an ajax request passing the serialized data.

If successful in this case you can pass back a Json Object. In my example I simply pass back a string that says "Success". So you will see an alert box now displaying Success in it, for my simple example.

function addRowsViaAJAX() {

    var d = new Date(); // IE hack to prevent caching

    $.getJSON('/ControllerName/ActionName', { Data: $('#MyForm').serialize(), Date: d.getTime() }, function(data) {
        // callback on success
        alert(data);
    }, 'json');
}

In you controller here's an example of an Action to use for AJAX Your data comes in serialized as a linear string so you will have to parse it, which is pretty easy. Then take the data and do your respective database logic. Then return a Json Object.

public virtual JsonResult ActionName(string data)
{
   // take the data and parse the linear stream... I like to use the FormCollection
   FormCollection collection = new FormCollection();

   foreach (string values in data.Split('&')){
     string[] value = values.Split('=');
     collection.Add(value[0], value[1]);
   }
   // Now do your database logic here
   return Json("Success");
}
Sign up to request clarification or add additional context in comments.

Comments

1

I would wrap that table in a form and then use the AJAX POST to send back the data to a server side page that actually does the insert.

$.ajax({
    type: 'POST',
    url: [URL_TO_PAGE_THAT_DOES_DB_INSERT],
    data: $(_('[YOURFORMID')).serialize(),
    success: function(data) {
               //do something

    }
        error: function(xhr){
              //do something else
        }
});

Comments

0

you can do this with the .ajax method

var prop= {};

prop["Name"] = $("#txtPropName").val();
prop["Address"] = $("#txtPropAddress").val();

$.ajax({
     type: "POST",
     contentType: "application/json; charset=utf-8",
     url: "/Admin/AddProperty",
     data: JSON.stringify(release),
     dataType: "json",
     success: function(result) {
          // do something on success                      

     },
     error: function(result) {
         // do something on error 
     }  
 });

Then in your controller you could do this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddProperty(Property prop)
{
   // add property to database, etc.        
   return Json(true);
}

You can get JSON.stringify from here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.