Wednesday, June 24, 2026

ASP.NET Core Razor Pages - Example of BindProperty

Step1. Set configuration for ASP.NET Core Razor Page in Program file
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();

var app = builder.Build();

app.UseDeveloperExceptionPage();

app.UseRouting();

app.MapRazorPages();

app.Run();
Step2. Input box and Button in front HTML page
@page
@model RazorPageWithTextBox.Pages.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<div>
    <form action="" method="post">
        @Html.AntiForgeryToken()
        <label for="inputText">Enter some text:</label>
        <input type="text" id="inputText" name="inputText" value="@Model.InputText" />
        <button type="submit">Submit</button>
    </form>
</div>
Step3. Backend code with BindProperty on InputText property
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPageWithTextBox.Pages
{
    public class IndexModel : PageModel
    {
        [BindProperty]
        public string? InputText { get; set; }
        public void OnPost()
        {
            Console.WriteLine("Test1: " + InputText);
            //Console.WriteLine("Test2: " + Request.Form["InputText"]);
        }
    }
}
Next:

No comments:

Post a Comment

Hot Topics