Asp.net

Sample 1

// call ASP.NET
$(document).ready(function () {
  $('#MyButton').click(function () {
       $.post('../GetCustomers.aspx',
               {PageSize:15}, 
               function (data) {
                $('#OutputDiv').html(data);
       });
  });
});
// GetCustomers.aspx
protected void Page_Load(object sender, EventArgs e)
 {
        var pageSize = (Request["PageSize"]==null)?50:Int32.Parse(Request["PageSize"]);
        var custs = new List<Customer>();
        for (int i = 1; i < pageSize; i++)
        {
            var cust = new Customer
                           {
                               FirstName = "John" + i.ToString(),
                               LastName = "Doe" + i.ToString()
                           };
            custs.Add(cust);
        }
        dlCustomers.DataSource = custs;
        dlCustomers.DataBind();
    }

Sample 2

$.getJSON('../CustomerJson.aspx',{id:1},
         function (data) {
           alert('CustomerID: ' + data.ID + ' Name: ' +
           data.FirstName + ' ' + data.LastName);
});
// CustomerJson.aspx
protected void Page_Load(object sender, EventArgs e)
{
        Response.ContentType = "application/json";
        var cust = new Customer
        {
            ID = int.Parse(Request["id"]),
            FirstName = "John",
            LastName = "Doe"
        };
        var ser = new DataContractJsonSerializer(typeof(Customer));
        ser.WriteObject(Response.OutputStream, cust);
}

ASP.NET MVC

Handling Exceptions using JQuery and ASp.NET MVC

Working with JQuery

private JsonResult ThrowJSONError(Exception e)
{
 Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
 //Log your exception
 return Json(new { Message = e.Message});
}

public ActionResult DivideByZero()
{
 try
 {
     throw new DivideByZeroException();
 }
 catch (DivideByZeroException e)
 {
     return ThrowJSONError(e);
 }
}

$(document).ready(function() {
 $.ajax({
 type: "GET",
 url: "AJAX/DivideByZero",
 dataType: "json",
 success: function(data) {
 if (data) {
 alert("Success!!!");
 }
 },

 error: function(xhr, status, error) {
 DisplayError(xhr);
 }
 });

});

function DisplayError(xhr) {
 var msg = JSON.parse(xhr.responseText);
 alert(msg.Message);
}

​ Alternative way:



$.ajax({

 type: 'POST',
 url: '/Account/UnfavoriteEvent',
 data: { id: $("#EventID").val() },
 success: function(data, textStatus, jqXHR) {
 // jqXHR.status contains the Response.Status set on the server
 },

 error: function(jqXHR, textStatus, errorThrown) {
 // jqXHR.status contains the Response.Status set on the server

 }});


[HttpPost]
public void UnfavoriteEvent(int id)
{
 try
 {
 var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID", new { EventID = id, UserName = User.Identity.Name });

 if (rows != 1)
 {
 return new HttpStatusCodeResult(500, "There was an unknown error updating the database.");
 }
 }
 catch (Exception ex) {

 return new HttpStatusCodeResult(500, ex.Message);

 }

}
Using with JQuery

results matching ""

    No results matching ""