Search code examples
c#formsasp.net-corerazor-pages

ASP.NET Razor Page - Set Other Class Variable From Form Input


I have a simple form as such:

'''
<form method="post">
    <label type="text" asp-for="@OtherClass.Key"/>
    <button type="submit" asp-page="Page">Submit</button>
</form>
'''

I am trying to get a string input and when the submit button is clicked, set a static string variable of another class to the input value.

'''
public class OtherClass {
    public static string Key { get; set; }
}
'''

I'm new to ASP.NET so I guess I'm generally asking how to set a static variable of a different class from a form?


Solution

  • You can not directly bind the input value to a static property.

    <form method="post">
        <input type="text" asp-for="Key" />
        <button type="submit" asp-page="Page">Submit</button>
    </form>
    

    Assign the input value to it in the post method.

    [BindProperty]
    public string Key { get; set; }
    
    public void OnGet()
    {
        Key = OtherClass.Key;
    }
    
    public void OnPost()
    {
        OtherClass.Key = Key;
    }