Friday, June 12, 2026

ASP.NET Core Razor Pages TextBox Focus Lost

Create ASP.NET Core Razor Pages application to display event handling for textbox.

Step1. Setup services and middleware in Program file required for ASP.NET Core Razor Pages application.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();

var app = builder.Build();

app.UseDeveloperExceptionPage();

app.UseRouting();

app.MapRazorPages();

app.Run();
Step2. In Razor Pages, design the UI for textbox. Add script with fetch API for posting textbox input data to server. The server responds to this request in terms of JSON data.
@page
@model RazorPageWithTextBoxChangeEvent.Pages.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<div align="center">
    <h1>ASP.NET Core Razor Pages TextBox Focus Lost</h1>
    <h4>Input some text in TextBox and press Tab and click mouse outside anywhere.</h4>
</div>
<div style="border-color:red;padding:10px;border-style:dashed;width:40%;margin-left:30%">
    <form method="post" action="">
        @Html.AntiForgeryToken()
        <label>Input Data</label>
        <input type="text" name="TextInput" id="TextInput" value="@Model.TextInput" />
    </form>

    <div id="show"></div>
</div>

<script>
    const text = document.getElementById("TextInput");
    const show = document.getElementById("show");
    text.addEventListener("change", async function (event) {
      event.preventDefault();
    // Get the anti-forgery token
    const antiForgeryToken = document.querySelector('input[name="__RequestVerificationToken"]').value;
      // Send textbox data to server using fetch() api
      fetch('/', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json', // Crucial: tell the server we're sending JSON
              'RequestVerificationToken': antiForgeryToken // Add the token to the header
          },
          body: JSON.stringify({ data: text.value }) // Send the value, wrapped in an object
      })
      .then(res => {
          if (!res.ok) { // Check for HTTP errors
              throw new Error(`HTTP error! status: ${res.status}`);
          }
          return res.json(); // Parse the JSON response
      })
      .then(d => {
          // Display response data
          let para = document.createElement('p');
          // Since OnPost now returns a JsonResult of the data, 'd' will be the string itself
          para.innerHTML = 'You entered: '+ d;
          console.log('d is',d);
          show.append(para);
      })
      .catch(err => console.log('Some error during posting data to server: ' + err));
    });
</script>
Step3. The Razor Pages backing code for event handling.
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPageWithTextBoxChangeEvent.Pages
{
    // Define a class to match the incoming JSON structure
    public class TextInputModel
    {
        public string? data { get; set; } // Property name 'Data' matches the 'data' key in your JSON
    }
    public class IndexModel : PageModel
    {
        [BindProperty(SupportsGet = true)] // Add this if you want TextInput to persist across GET requests
        public string? TextInput { get; set; }

        // OnPost is called for POST requests
        public async Task<JsonResult> OnPost([FromBody] TextInputModel input)
        {
            // The [FromBody] attribute explicitly tells ASP.NET Core to read the 'data'
            // parameter from the request body. If the client sends a raw string in the body
            // without being wrapped in an object (e.g., just "hello"), this would work.
            // However, since we're sending { data: "value" } from the client,
            // the model binder will look for a property named 'data' in the JSON.
            // A simpler approach for the client's current sending method is to
            // keep OnPost(string? data) and let model binding work.

            // Let's ensure the data is received. If you send { data: "value" },
            // then 'data' will be bound correctly to "value".

            await Task.Delay(1); // Simulate some async work
            return new JsonResult(input?.data); // Return the received data as JSON
        }
    }
}
Next:

No comments:

Post a Comment

Hot Topics