AJAX ASP

Using AJAX with ASP.NET backend

🔷 AJAX + ASP.NET

Learn how to use AJAX with ASP.NET to create dynamic web applications. ASP.NET provides powerful server-side processing for your AJAX requests!


// JavaScript calls ASP.NET Web Method
fetch('/Default.aspx/GetUserData', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ userId: 123 })
})
.then(response => response.json())
.then(data => console.log(data.d));
                                    

AJAX ASP.NET Methods

🎯

Web Methods

Static methods called via AJAX

[WebMethod]
public static string GetData()
🌐

Web Services

ASMX services for AJAX

[WebService]
public class DataService
🚀

Web API

RESTful APIs for modern apps

[ApiController]
public class UsersController
📊

JSON Results

Return structured data

return Json(data);

🔹 ASP.NET Web Methods

Web Methods are the simplest way to handle AJAX in ASP.NET:

🔸 ASP.NET Code-Behind (C#)

// Default.aspx.cs
using System;
using System.Web.Services;
using System.Web.Script.Services;

public partial class Default : System.Web.UI.Page
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object GetUserInfo(int userId)
    {
        // Simulate database lookup
        var user = new
        {
            Id = userId,
            Name = "John Doe",
            Email = "[email protected]",
            Department = "IT"
        };
        
        return user;
    }
    
    [WebMethod]
    public static string SaveUserData(string name, string email)
    {
        // Save to database logic here
        // For demo, just return success message
        return $"User {name} saved successfully!";
    }
}

🔸 JavaScript (Frontend)

// Call Web Method
function loadUser(userId) {
  fetch('/Default.aspx/GetUserInfo', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify({ userId: userId })
  })
  .then(response => response.json())
  .then(data => {
    const user = data.d; // ASP.NET wraps result in 'd' property
    document.getElementById('user-info').innerHTML = `
      <h3>${user.Name}</h3>
      <p>Email: ${user.Email}</p>
      <p>Department: ${user.Department}</p>
    `;
  })
  .catch(error => console.error('Error:', error));
}

Result:

John Doe

Email: [email protected]

Department: IT

🔹 ASP.NET Web API Example

Web API provides a more modern approach for AJAX communication:

🔸 Web API Controller

// Controllers/UsersController.cs
using System.Web.Http;

public class UsersController : ApiController
{
    // GET api/users/5
    public IHttpActionResult Get(int id)
    {
        var user = new
        {
            Id = id,
            Name = "Jane Smith",
            Email = "[email protected]",
            Role = "Manager"
        };
        
        return Ok(user);
    }
    
    // POST api/users
    public IHttpActionResult Post([FromBody]UserModel user)
    {
        // Validate and save user
        if (string.IsNullOrEmpty(user.Name))
        {
            return BadRequest("Name is required");
        }
        
        // Save to database logic here
        
        return Ok(new { message = "User created successfully", id = 123 });
    }
}

public class UserModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Role { get; set; }
}

🔸 JavaScript API Calls

// GET request to Web API
function getUser(id) {
  fetch(`/api/users/${id}`)
    .then(response => response.json())
    .then(user => {
      document.getElementById('user-display').innerHTML = `
        <div class="user-card">
          <h3>${user.Name}</h3>
          <p>Email: ${user.Email}</p>
          <p>Role: ${user.Role}</p>
        </div>
      `;
    });
}

// POST request to Web API
function createUser(userData) {
  fetch('/api/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(userData)
  })
  .then(response => response.json())
  .then(result => {
    if (result.message) {
      alert(result.message);
    }
  })
  .catch(error => {
    console.error('Error:', error);
  });
}

🔹 UpdatePanel Alternative

While UpdatePanel exists, modern AJAX is preferred:

❌ Old Way (UpdatePanel):

  • Heavy ViewState
  • Full page lifecycle
  • Limited control
  • Performance issues

✅ Modern Way (AJAX + Web API):

  • Lightweight JSON
  • Fast responses
  • Full control
  • Better performance

🔸 Modern AJAX Form

<form id="user-form">
  <input type="text" id="userName" placeholder="Name" required>
  <input type="email" id="userEmail" placeholder="Email" required>
  <select id="userRole">
    <option value="User">User</option>
    <option value="Admin">Admin</option>
  </select>
  <button type="submit">Save User</button>
</form>

<script>
document.getElementById('user-form').addEventListener('submit', function(e) {
  e.preventDefault();
  
  const userData = {
    Name: document.getElementById('userName').value,
    Email: document.getElementById('userEmail').value,
    Role: document.getElementById('userRole').value
  };
  
  createUser(userData);
});
</script>

🧠 Test Your Knowledge

What attribute is required for ASP.NET Web Methods?