Issue: How to trim text using asp-for
tag & razor page?
Detail: I have a input field where user can enter there firstname
. I noticed user can enter multi spaces or tabs. Since I am using asp-for
tag, it will auto bind the data to Person
object on OnPost()
Method
I am trying not to use following methods Request.Form("firstname").trim()
or pass value though OnPost(string firstname)
Method; Because whole point of asp-for
tag is to auto bind your values to object rather than manually getting each values like using name
tag.
If there isn't any way to do this, than what is the point of asp.for
tag? bc in real world you will end up checking for extra spaces any ways.
<input asp-for="Person.FirstName" />
<span asp-validation-for="Person.FirstName" ></span>
[BindProperty]
public Person_Model Person { get; set; } = default!;
[BindProperty(SupportsGet = true)]
public string? FirstName{ get; set; }
public async Task<IActionResult> OnPostAsync()
{
// here First_name can have spaces
_context2.my_DbSet.Add(Person);
await _context2.SaveChangesAsync();
}
public class Person_Model
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 Id { get; set; }
public string? FirstName{ get; set; }
}
I tried adding RegularExpression, but this will just give me error if there is whtie space inside text-field. I just want to trim it.
[RegularExpression(@"[^\s] ")]
public string? FirstName{ get; set; }
CodePudding user response:
First of all in case the FirstName is a required field, you have to add the Required attribute.
public class Person_Model
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 Id { get; set; }
[Required]
public string? FirstName { get; set; }
}
Now in your OnPostAsync method you first have to check for validation errors and return to page in order to display the error messages.
You can also trim your FirstName if you want and then continue saving the record in your database.
public async Task<IActionResult> OnPostAsync()
{
// validate the model. in case there are validation errors return to page and display them
if (!ModelState.IsValid)
{
return Page();
}
// trim your first name in case there are spaces
Person.FirstName = Person.FirstName?.Trim();
// here First_name can have spaces
_context2.my_DbSet.Add(Person);
await _context2.SaveChangesAsync();
return Page();
}
I hope it helps.