Submit a Form To ASP.NET Core Razor Pages

In this post, I would like to show how to create a form with ASP.NET Core Razor pages and submit it using a PageModel to process the data.

ASP.NET Core Razor pages give us at least four options to process requests (using forms or get), and in the post, I will focus on one that I think is ideal and secure

The Form

Let’s get started and review the form that I have created for this post. As you can see, it is a simple form with two options, and a submit button to submit the code.

The Code

The code for the form is below and the file name is index.cshtml

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<form action="/index" method="post" asp-antiforgery="true">
        <label for="selectlenth">Select value</label>
        <select name="pLenth" id="lenth">
            <option value="8" > 8</option>
            <option value="12">12</option>
            <option value="16">16</option>
            <option value="20">20</option>
            <option value="24">24</option>
  </select>
     <br>
       Enter name<input name="Name" type="text"> </input> 
       <br>
       <input type="submit" value="Submit">
    </form>

 
 @if (@Model.pLenth>0)
    {
    <p><h3>@Model.pLenth </h3</p>
     <p><h3>@Model.Name </h3</p>
   
    }
     

Model Binding

The next step is to bind the submitted values to the PageModel and present them to the user from Razor Page.

The configuration is located in the index.cshtml.cs (usually you will find the .cs file under the .cshtml file in an ASP.NET Razor project)

Just a few notes about the code below. The page Handler method is public void OnPost(), and the two values sent from the form are pLenth and Name (The appear under [BindProperty] ). Inside the handler, I’m doing a small calculation on the pLenth value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace aspform.Pages
{
    public class IndexModel : PageModel
    {
       
      
        private readonly ILogger<IndexModel> _logger;

        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {

        }

        [BindProperty]
         public int pLenth { get; set; }
        [BindProperty]
        public string Name { get; set;}

        public void OnPost()
        {
            pLenth = pLenth * 4;
            Name = Name;
        
        }

   

    }
}

Outcome

The result is shown below (I submitted the form with value 8 and the name ntweekly, and I’m simply printing the code out.

For more .NET posts, visit the .NET category page.


Posted

in

by