JQUERY - INTERVIEW QUESTIONS AND ANSWERS
Q1: What is jQuery and why is it used in ASP.NET Core?
Answer: jQuery is a fast, lightweight, and feature-rich JavaScript library that simplifies HTML document traversal, event handling, animating, and Ajax interactions. In ASP.NET Core, jQuery is commonly used for:
Making AJAX calls to controllers
DOM manipulation and validation
Handling client-side events
Enhancing UI interactions
Example in ASP.NET Core:
$.ajax({ type: "POST", url: "/Employees/Create", data: { name: "John", salary: 50000 }, success: function(response) { $("#result").html("Employee added successfully"); } });
Q2: How do you include jQuery in an ASP.NET Core project?
Answer: There are multiple ways:
Option 1: Using CDN (most common)
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Option 2: Using LibMan (Library Manager)
// libman.json
{
"libraries": [
{
"library": "jquery@3.6.0",
"destination": "wwwroot/lib/jquery"
}
]
}Option 3: Using npm/package.json
{ "dependencies": { "jquery": "3.6.0" } }
Q3: What is the difference between $(document).ready() and $(window).load()?
Answer:
| $(document).ready() | $(window).load() |
|---|---|
| Executes when DOM is ready (HTML loaded) | Executes when entire page including images, CSS, scripts are loaded |
| Multiple instances can be used | Only one instance |
| Faster execution | Slower execution |
Can be written as $(function(){}) | Must use full syntax |
Example:
// Document Ready - Most common in ASP.NET Core $(document).ready(function() { $("#btnSave").click(function() { // This works as soon as button exists }); }); // Window Load - For image-dependent operations $(window).on('load', function() { $("#image").height(); // Image dimensions are now available });
Q4: How do you make an AJAX call to an ASP.NET Core Controller?
Answer:
ASP.NET Core Controller:
[HttpPost] public IActionResult GetEmployee(int id) { var employee = _context.Employees.Find(id); return Json(employee); }
jQuery AJAX call:
$.ajax({ url: '/Employees/GetEmployee', type: 'GET', data: { id: 5 }, dataType: 'json', success: function(data) { console.log(data.name); $('#name').val(data.name); }, error: function(xhr, status, error) { alert('Error: ' + error); } });
Q5: How do you handle Anti-Forgery Token in jQuery AJAX calls?
Answer:
In Razor View:
<form id="myForm"> @Html.AntiForgeryToken() <!-- form fields --> </form>
jQuery AJAX:
$("#btnSave").click(function() { var token = $('input[name="__RequestVerificationToken"]').val(); $.ajax({ type: "POST", url: "/Employees/Create", data: { Name: "John", Salary: 50000 }, headers: { "RequestVerificationToken": token }, success: function(response) { alert("Success"); } }); });
Intermediate Level Questions
Q6: Explain event delegation in jQuery with an ASP.NET Core example
Answer: Event delegation allows you to attach events to elements that exist now or in the future. This is crucial in ASP.NET Core when dealing with dynamically loaded content.
Problem: Buttons loaded via AJAX don't have events attached
// This WON'T work for dynamically added buttons $(".delete-btn").click(function() { // Not triggered for AJAX-loaded buttons }); // This WILL work using event delegation $(document).on("click", ".delete-btn", function() { var id = $(this).data("id"); $.ajax({ url: "/Employees/Delete/" + id, type: "POST", success: function() { $(this).closest("tr").remove(); } }); });
Q7: How do you serialize form data in jQuery for ASP.NET Core?
Answer:
HTML Form:
<form id="employeeForm"> <input type="text" name="Name" id="name" /> <input type="number" name="Salary" id="salary" /> <select name="DepartmentId" id="department"> <option value="1">IT</option> <option value="2">HR</option> </select> </form>
jQuery Serialization:
// Method 1: serialize() - creates query string var formData = $("#employeeForm").serialize(); // Result: Name=John&Salary=50000&DepartmentId=1 // Method 2: serializeArray() - creates array of objects var formArray = $("#employeeForm").serializeArray(); // Result: [{name: "Name", value: "John"}, ...] // Method 3: Custom object (most used with ASP.NET Core) var formObject = {}; $("#employeeForm").serializeArray().map(function(item) { formObject[item.name] = item.value; }); $.ajax({ url: "/Employees/Create", type: "POST", data: formObject, // ASP.NET Core binds this to your model success: function() { } });
Q8: How do you implement client-side validation using jQuery in ASP.NET Core?
Answer:
HTML with validation spans:
<div class="form-group"> <label>Name</label> <input type="text" id="name" class="form-control" /> <span id="nameError" class="text-danger"></span> </div>
jQuery Validation:
function validateForm() { var isValid = true; // Name validation var name = $("#name").val().trim(); if (!name) { $("#nameError").text("Name is required"); isValid = false; } else if (name.length < 2) { $("#nameError").text("Name must be at least 2 characters"); isValid = false; } else { $("#nameError").text(""); } // Email validation with regex var email = $("#email").val().trim(); var emailPattern = /^[^\s@@]+@@[^\s@@]+\.[^\s@@]+$/; if (!emailPattern.test(email)) { $("#emailError").text("Invalid email format"); isValid = false; } return isValid; } $("#btnSave").click(function(e) { e.preventDefault(); if (validateForm()) { // Submit form } });
Q9: Explain different jQuery AJAX methods and their use in ASP.NET Core
Answer:
// 1. $.ajax() - Most configurable $.ajax({ url: "/api/employees", type: "POST", data: JSON.stringify(employee), contentType: "application/json", dataType: "json", beforeSend: function() { $("#loader").show(); }, complete: function() { $("#loader").hide(); }, success: function(data) { console.log(data); }, error: function(xhr) { console.log(xhr.status); } }); // 2. $.get() - Simplified GET request $.get("/Employees/Details/5", function(data) { $("#details").html(data); }); // 3. $.post() - Simplified POST request $.post("/Employees/Create", { name: "John" }, function(response) { alert("Created"); }); // 4. $.getJSON() - For JSON responses $.getJSON("/api/employees", function(data) { $.each(data, function(i, emp) { $("#empList").append("<li>" + emp.name + "</li>"); }); }); // 5. $.load() - Load HTML directly $("#container").load("/Employees/PartialView/5");
Q10: How do you chain promises in jQuery AJAX for dependent calls?
Answer:
// Scenario: Get department, then get employees in that department $.ajax({ url: "/Departments/Get/5", type: "GET" }).then(function(department) { // First AJAX complete console.log("Department: " + department.name); // Return second AJAX call return $.ajax({ url: "/Employees/ByDepartment/" + department.id, type: "GET" }); }).then(function(employees) { // Second AJAX complete console.log("Found " + employees.length + " employees"); // Process employees $.each(employees, function(i, emp) { $("#empTable").append("<tr><td>" + emp.name + "</td></tr>"); }); }).fail(function(error) { // Handle any error in the chain console.error("Error in chain: ", error); });
Advanced Level Questions
Q11: How do you implement cascading dropdowns using jQuery in ASP.NET Core?
Answer:
HTML:
<select id="country" class="form-control"> <option value="">Select Country</option> </select> <select id="city" class="form-control" disabled> <option value="">Select City</option> </select>
jQuery Implementation:
$(document).ready(function() { // Load Countries $.getJSON("/Location/GetCountries", function(countries) { $.each(countries, function(i, country) { $("#country").append($('<option>', { value: country.id, text: country.name })); }); }); // Country change event $("#country").change(function() { var countryId = $(this).val(); if (countryId) { $("#city").prop("disabled", false); // Load Cities for selected country $.getJSON("/Location/GetCities", { countryId: countryId }, function(cities) { $("#city").empty().append('<option value="">Select City</option>'); $.each(cities, function(i, city) { $("#city").append($('<option>', { value: city.id, text: city.name })); }); }); } else { $("#city").prop("disabled", true).empty() .append('<option value="">Select City</option>'); } }); });
Q12: How do you implement infinite scrolling with jQuery in ASP.NET Core?
Answer:
Controller:
public IActionResult GetEmployees(int page = 1, int pageSize = 10) { var employees = _context.Employees .Skip((page - 1) * pageSize) .Take(pageSize) .ToList(); return Json(employees); }
jQuery Implementation:
var page = 1; var isLoading = false; var hasMore = true; $(window).scroll(function() { if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) { if (!isLoading && hasMore) { loadMoreEmployees(); } } }); function loadMoreEmployees() { isLoading = true; $("#loader").show(); $.getJSON("/Employees/GetEmployees", { page: page, pageSize: 10 }, function(data) { if (data.length === 0) { hasMore = false; $("#noMoreData").show(); } else { $.each(data, function(i, emp) { $("#empList").append( '<div class="employee-item">' + '<h4>' + emp.name + '</h4>' + '<p>' + emp.designation + '</p>' + '</div>' ); }); page++; } isLoading = false; $("#loader").hide(); }); }
Q13: How do you implement real-time search/filter using jQuery?
Answer:
HTML:
<input type="text" id="searchInput" placeholder="Search employees..." /> <table id="employeeTable"> <thead> <tr> <th>Name</th> <th>Designation</th> <th>Department</th> </tr> </thead> <tbody id="tableBody"> <!-- Data loaded via AJAX --> </tbody> </table>
jQuery Implementation with Debouncing:
var searchTimeout; // Debounce function to prevent too many AJAX calls $("#searchInput").on("keyup", function() { clearTimeout(searchTimeout); var searchTerm = $(this).val(); searchTimeout = setTimeout(function() { if (searchTerm.length >= 2 || searchTerm.length === 0) { performSearch(searchTerm); } }, 500); // Wait 500ms after user stops typing }); function performSearch(searchTerm) { $("#loader").show(); $.ajax({ url: "/Employees/Search", type: "GET", data: { term: searchTerm }, success: function(employees) { var tbody = $("#tableBody"); tbody.empty(); if (employees.length === 0) { tbody.append('<tr><td colspan="3">No employees found</td></tr>'); } else { $.each(employees, function(i, emp) { tbody.append( '<tr>' + '<td>' + emp.name + '</td>' + '<td>' + emp.designation + '</td>' + '<td>' + emp.department + '</td>' + '</tr>' ); }); } }, complete: function() { $("#loader").hide(); } }); }
Q14: How do you handle file upload with progress bar using jQuery?
Answer:
HTML:
<form id="uploadForm" enctype="multipart/form-data"> <input type="file" id="fileInput" name="file" /> <button type="button" id="btnUpload">Upload</button> </form> <div class="progress" style="display:none;"> <div class="progress-bar" id="progressBar" style="width: 0%;">0%</div> </div>
jQuery Implementation:
$("#btnUpload").click(function() { var file = $("#fileInput")[0].files[0]; if (!file) { alert("Please select a file"); return; } var formData = new FormData(); formData.append("file", file); $(".progress").show(); $.ajax({ url: "/Documents/Upload", type: "POST", data: formData, contentType: false, processData: false, xhr: function() { var xhr = new window.XMLHttpRequest(); // Upload progress xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = Math.round((evt.loaded / evt.total) * 100); $("#progressBar").css("width", percentComplete + "%") .text(percentComplete + "%"); } }, false); return xhr; }, success: function(response) { alert("File uploaded successfully"); setTimeout(function() { $(".progress").hide(); $("#progressBar").css("width", "0%").text("0%"); }, 2000); }, error: function() { alert("Upload failed"); $(".progress").hide(); } }); });
Q15: How do you implement CRUD operations with jQuery and ASP.NET Core?
Answer:
Complete CRUD Example:
var EmployeeManager = { // Initialize init: function() { this.loadEmployees(); this.bindEvents(); }, // Bind events bindEvents: function() { $("#btnSave").click(this.saveEmployee); $("#btnUpdate").click(this.updateEmployee); $(document).on("click", ".edit-btn", this.editEmployee); $(document).on("click", ".delete-btn", this.deleteEmployee); }, // Load all employees loadEmployees: function() { $.getJSON("/Employees/GetAll", function(employees) { var tbody = $("#employeeTable tbody"); tbody.empty(); $.each(employees, function(i, emp) { tbody.append( '<tr>' + '<td>' + emp.name + '</td>' + '<td>' + emp.designation + '</td>' + '<td>' + emp.salary + '</td>' + '<td>' + '<button class="edit-btn" data-id="' + emp.id + '">Edit</button>' + '<button class="delete-btn" data-id="' + emp.id + '">Delete</button>' + '</td>' + '</tr>' ); }); }); }, // Create employee saveEmployee: function(e) { e.preventDefault(); var employee = { Name: $("#name").val(), Designation: $("#designation").val(), Salary: $("#salary").val() }; var token = $('input[name="__RequestVerificationToken"]').val(); $.ajax({ url: "/Employees/Create", type: "POST", data: employee, headers: { "RequestVerificationToken": token }, success: function() { $("#createModal").modal('hide'); EmployeeManager.loadEmployees(); EmployeeManager.clearForm(); } }); }, // Edit employee editEmployee: function() { var id = $(this).data('id'); $.getJSON("/Employees/Get/" + id, function(emp) { $("#editId").val(emp.id); $("#editName").val(emp.name); $("#editDesignation").val(emp.designation); $("#editSalary").val(emp.salary); $("#editModal").modal('show'); }); }, // Update employee updateEmployee: function(e) { e.preventDefault(); var employee = { Id: $("#editId").val(), Name: $("#editName").val(), Designation: $("#editDesignation").val(), Salary: $("#editSalary").val() }; var token = $('#editForm input[name="__RequestVerificationToken"]').val(); $.ajax({ url: "/Employees/Edit", type: "POST", data: employee, headers: { "RequestVerificationToken": token }, success: function() { $("#editModal").modal('hide'); EmployeeManager.loadEmployees(); } }); }, // Delete employee deleteEmployee: function() { if (!confirm("Are you sure?")) return; var id = $(this).data('id'); var token = $('input[name="__RequestVerificationToken"]').val(); $.ajax({ url: "/Employees/Delete/" + id, type: "POST", headers: { "RequestVerificationToken": token }, success: function() { EmployeeManager.loadEmployees(); } }); }, // Clear form clearForm: function() { $("#name, #designation, #salary").val(""); } }; // Initialize on document ready $(document).ready(function() { EmployeeManager.init(); });
Q16: What are jQuery Deferred objects and how are they used?
Answer:
// Custom Deferred object function validateAndSave() { var deferred = $.Deferred(); // Validate first if ($("#name").val().trim() === "") { deferred.reject("Name is required"); } else { // Save data $.ajax({ url: "/Employees/Save", type: "POST", data: { name: $("#name").val() }, success: function(response) { deferred.resolve(response); }, error: function() { deferred.reject("Save failed"); } }); } return deferred.promise(); } // Usage validateAndSave().done(function(response) { alert("Success: " + response); }).fail(function(error) { alert("Error: " + error); }); // Multiple parallel AJAX calls $.when( $.ajax("/Employees/GetAll"), $.ajax("/Departments/GetAll"), $.ajax("/Projects/GetAll") ).then(function(employees, departments, projects) { // All three calls completed console.log("Employees:", employees[0]); console.log("Departments:", departments[0]); console.log("Projects:", projects[0]); }).fail(function() { console.log("One of the calls failed"); });
Q17: How do you optimize jQuery performance in ASP.NET Core applications?
Answer:
// 1. Cache jQuery selectors // BAD $("#name").val("John"); $("#name").addClass("valid"); $("#name").css("color", "green"); // GOOD var $name = $("#name"); $name.val("John"); $name.addClass("valid"); $name.css("color", "green"); // 2. Use find() instead of context selectors // BAD $("#employeeTable .employee-row .employee-name"); // GOOD $("#employeeTable").find(".employee-row").find(".employee-name"); // 3. Chain methods // BAD $("#name").addClass("valid"); $("#name").val("John"); $("#name").css("color", "green"); // GOOD $("#name").addClass("valid").val("John").css("color", "green"); // 4. Use specific selectors // BAD $("div[data-id='5']"); // GOOD (if possible) $("#employee-5"); // 5. Detach elements before multiple manipulations var $table = $("#employeeTable"); var $tbody = $table.find("tbody").detach(); for (var i = 0; i < 100; i++) { $tbody.append("<tr><td>Row " + i + "</td></tr>"); } $table.append($tbody); // 6. Use event delegation for dynamic elements // BAD $(".delete-btn").click(function() { }); // GOOD $(document).on("click", ".delete-btn", function() { }); // 7. Throttle/Debounce expensive operations var resizeTimer; $(window).on("resize", function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(function() { // Expensive resize operation console.log("Resize complete"); }, 250); });
Q18: How do you handle AJAX errors globally in jQuery?
Answer:
// Global AJAX error handler $(document).ajaxError(function(event, jqxhr, settings, thrownError) { console.log("AJAX Error:", thrownError); var status = jqxhr.status; var response = jqxhr.responseJSON; switch(status) { case 400: showNotification("Bad request: " + response.message, "error"); break; case 401: showNotification("Your session has expired. Please login again.", "warning"); setTimeout(function() { window.location.href = "/Account/Login"; }, 2000); break; case 403: showNotification("You don't have permission to perform this action.", "error"); break; case 404: showNotification("Resource not found.", "error"); break; case 500: showNotification("Server error. Please try again later.", "error"); break; default: showNotification("An error occurred: " + thrownError, "error"); } }); // Global AJAX start/complete handlers $(document).ajaxStart(function() { $("#globalLoader").show(); }); $(document).ajaxComplete(function() { $("#globalLoader").hide(); }); // Custom notification function function showNotification(message, type) { var notification = $('<div class="notification ' + type + '">' + message + '</div>'); $("body").append(notification); setTimeout(function() { notification.fadeOut(function() { $(this).remove(); }); }, 3000); }
Q19: How do you implement a jQuery plugin in ASP.NET Core?
Answer:
Creating a custom jQuery plugin:
// Custom validation plugin (function($) { $.fn.validateEmployee = function(options) { var settings = $.extend({ nameRequired: true, salaryRequired: true, minSalary: 0, onError: function() { } }, options); return this.each(function() { var $form = $(this); var isValid = true; // Name validation if (settings.nameRequired) { var $name = $form.find("#name"); if ($name.val().trim() === "") { $name.addClass("input-error"); $form.find("#nameError").text("Name is required"); isValid = false; } else { $name.removeClass("input-error"); } } // Salary validation if (settings.salaryRequired) { var $salary = $form.find("#salary"); var salaryVal = parseFloat($salary.val()); if (isNaN(salaryVal) || salaryVal < settings.minSalary) { $salary.addClass("input-error"); $form.find("#salaryError").text("Invalid salary"); isValid = false; } else { $salary.removeClass("input-error"); } } if (!isValid && settings.onError) { settings.onError.call(this); } return isValid; }); }; }(jQuery)); // Usage in ASP.NET Core view $(document).ready(function() { $("#btnSave").click(function(e) { e.preventDefault(); var isValid = $("#employeeForm").validateEmployee({ nameRequired: true, salaryRequired: true, minSalary: 10000, onError: function() { $("#errorSummary").show(); } }); if (isValid) { // Submit form $("#employeeForm").submit(); } }); });
Q20: How do you handle complex nested JSON data in jQuery?
Answer:
ASP.NET Core returns nested JSON:
public class EmployeeWithDetails { public int Id { get; set; } public string Name { get; set; } public Department Department { get; set; } public List<Project> Projects { get; set; } public Dictionary<string, object> Metadata { get; set; } } // Controller returns complex object return Json(employeeWithDetails);
jQuery handling:
$.ajax({ url: "/Employees/GetWithDetails/5", type: "GET", dataType: "json", success: function(data) { // Access nested properties console.log("Employee:", data.name); console.log("Department:", data.department.name); // Loop through projects array $.each(data.projects, function(i, project) { $("#projects").append( '<li>' + project.name + ' (' + project.status + ')</li>' ); }); // Access dictionary/metadata $.each(data.metadata, function(key, value) { console.log(key + ": " + value); }); // Build complex HTML var html = '<div class="employee-card">' + '<h3>' + data.name + '</h3>' + '<p>Department: ' + data.department.name + '</p>' + '<h4>Projects:</h4>' + '<ul>'; $.each(data.projects, function(i, project) { html += '<li class="project-' + project.status.toLowerCase() + '">' + project.name + ' - ' + project.status + '</li>'; }); html += '</ul></div>'; $("#employeeDetails").html(html); } });
Comments
Post a Comment