Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net razor razor-pages

cshtml aspfor getter not working but the setter

发布于 2020-03-27 10:21:15

I try to get the data of an input via asp-for from a cshtml page to a cshtml.cs page.

cshtml

<div class="form-group">
    <label class="col-sm-2 control-label">Name</label>
    <div class="col-sm-10">
        <textarea name="InputNameEvent" asp-for="NameEvent" class="form-control" placeholder="Name"></textarea>
    </div>
</div>

cshtml.cs

[Required]
[MinLength(5)]
[MaxLength(1024)]
public string NameEvent { get; set; }

public string Name2;

public void OnGet()
{
  NameEvent = "Test";
}
 public void OnPost()
 {
     Name2 = NameEvent;
 }

Test is shown in the Textarea, but in OnPost() NameEvent is NULL

Questioner
Kai
Viewed
72
Kai 2019-07-04 18:19

I found my mistake. I needed to put <form method="post"></form> around the div. ALso i needed to add [BindProperty] in cshtml.cs and remove the name attribute in cshtml. Thanks to Mike :)

cshtml

<form method="post">
<div class="form-group">
    <label class="col-sm-2 control-label">Name</label>
    <div class="col-sm-10">
        <textarea asp-for="NameEvent" class="form-control" placeholder="Name"></textarea>
    </div>
</div>
</form>

cshtml.cs

[Required]
[MinLength(5)]
[MaxLength(1024)]
[BindProperty]
public string NameEvent { get; set; }