1. this may html
2. i want to pass id="hostname" to c#.net homecontroller. how?
1. this may html
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajkiran SwainRank #165 · 14.4K reputationPosted Jun 1, 2023, 2:18 PM EDT
function sendHostname() { var hostname = document.getElementById("hostname").innerText; // Create an AJAX request var xhr = new XMLHttpRequest(); // Define the request method, URL, and asynchronous flag xhr.open("POST", "/Home/GetHostname", true); // Set the request header (optional) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Define the callback function to handle the response xhr.onload = function() { if (xhr.status === 200) { var response = xhr.responseText; // Handle the response from the server console.log("Response from server:", response); } }; // Send the request with the hostname as data xhr.send("hostname=" + encodeURIComponent(hostname)); }public class HomeController : Controller { [HttpPost] public ActionResult GetHostname(string hostname) { // Handle the received hostname in the controller // You can process the hostname or store it in a database, etc. // Example: Log the hostname to the console Console.WriteLine("Received hostname:", hostname); // Return a response to the client (optional) return Content("Hostname received successfully"); } }Amit MohantyRank #112 · 20K reputationPosted Jun 1, 2023, 5:46 AM EDT
Add an action method in your controller to receive the data:
public ActionResult GetHostname(string hostname) { // Do something with the hostname value // For example, you can store it in a database or process it further // Return a response if needed return Content("Hostname received successfully"); }Modify your HTML form to include a button or an event that triggers the AJAX request. For example:
Hostname : Submit function sendHostnameToController() { var hostname = document.getElementById("hostname").innerText; $.ajax({ url: '@Url.Action("GetHostname", "Home")', // Replace "Home" with your actual controller name type: 'POST', data: { hostname: hostname }, success: function (response) { console.log(response); // Handle the response from the controller if needed }, error: function (xhr, status, error) { console.log(error); // Handle the error if needed } }); }