Rob Crowell
Rob Crowell

Reputation: 1485

Default values and validation in ASP RazorPage

My PageModel has a single BindProperty like ?Query=, whose length should not exceed 1000. However, I also want this string to always be defined; on initial page load (or if a blank form is submitted), I want to use the default value "*" instead of null or "":

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;

namespace RazorTestApp.Pages;

public class IndexModel : PageModel
{
    [BindProperty(SupportsGet = true)]
    [StringLength(1000)]
    [Required(AllowEmptyStrings = false)]
    public string Query { get; set; } = "*";

    public void OnGet()
    {
    }
}

I have an equally simple View:

@page
@model IndexModel

<div class="text-center">
    <form method="get">
        @Html.EditorForModel()
        <div>
            <input type="submit" />
        </div>
    </form>
</div>

I am having 2 issues with this:

  1. Load page with no query string (initial load): the input box correctly displays "*", but I also get a validation error "The Query field is required".

  2. Load page with ?Query= (submit with empty query): the input box does not show the default "*" (shows empty string), and I get the same validation error "The Query field is required".

I am obviously not doing this correctly. How can I set a default value for Query to be used whenever it is empty/not provided, and have it play nicely with validation?

Upvotes: 0

Views: 1231

Answers (1)

Deepak-MSFT
Deepak-MSFT

Reputation: 11365

I tried to test the validations on my side.

Below is my model:

[BindProperty(SupportsGet = true), Required, StringLength(1000)]
        
public string Rating { get; set; } = "*";

View:

<div class="form-group">
     <label asp-for="Movie.Rating" class="control-label"></label>
     <input asp-for="Movie.Rating" class="form-control" />
     <span asp-validation-for="Movie.Rating" class="text-danger"></span>
</div>

Output:

enter image description here

On my side, I could see that * is added to the input field and if I remove it and submit the form then I get the validation message.

For testing purposes, I would suggest you make a test with the <form method="post">. If the issue persists then creating a new model and view and trying to test it separately may help to narrow down the issue.

Upvotes: 0

Related Questions