I want to be able to access and modify attributes of HTML elements of a page in my server side code (I am using ASP.NET Core Razor Pages 6.0).
For example: a .cshtml
file, I have a simple element like this:
<div >
<label asp-for="User.firstname" >First Name:</label>
<input asp-for="User.firstname" placeholder="First Name">
</div>
How do I access & change attributes of the above <input>
element inside the OnGet
or OnPost
server-side methods?
I need to do so as I want to add a class to that <input>
element, or make it read-only (depending on certain conditions in my server code).
In older versions of .NET, I believe this was possible by giving an HTML element an ID, and writing runat="server". Then, one could access the element in the code-behind via its ID and change its attributes. How is this done now in Razor Pages? Should I not be able to do the same because of the asp-for tag helper which I used inn my code above? But how?
Thank you for your help!
CodePudding user response:
you can achieve sending Value to the server with
This at razor page:
<form method="post">
<div >
<input name="title" placeholder="Type title here.." />
<button type="submit" >Post</button>
</form>
This at Model Page
public async Task<IActionResult> OnPostAsync(string title)
{
//do your stuff
}
Put breakpoint at public async Taks and viola.
I believe this should do the trick. You can change it for yourself.
CodePudding user response:
Here is a whole working demo you could follow:
Model
public class User
{
public string firstname { get; set; }
}
Page(.cshtml file)
@page
@model IndexModel
<form method="post">
<div >
<label asp-for="User.firstname" >First Name:</label>
<input asp-for="User.firstname" placeholder="First Name">
</div>
<input type="submit" value="Post"/>
</form>
PageModel(.cshtml.cs file)
1.For model binding of the element, one way is that you can use [BindProperty]
:
public class IndexModel : PageModel
{
[BindProperty]
public User User { get; set; }
public void OnGet()
{
}
public void OnPost()
{
//do your stuff.....
}
}
2.The second way is that you can add parameters like below:
public class IndexModel : PageModel
{
public User User { get; set; }
public void OnGet()
{
}
public void OnPost(User User)
{
}
}