Changing class (or other attributes) of HTML element in server side code (Razor Pages)

mauian 1 Reputation point
2022-11-19T16:16:12.74+00:00

Hello,

I am using ASP.NET Core Razor Pages 6.0.

In a .cshtml file, I have a simple element like this:

<div class="mb-3 mt-3">
<label asp-for="User.firstname" class="form-label">First Name:</label>
<input asp-for="User.firstname" class="form-control" placeholder="First Name">
</div>

How do I access & change the above <input> element inside the 'OnGet' or 'OnPost' methods?

I need to do so as I want to add a certain class to that <input> element, or make it readonly (depending on certain conditions in my server code).

In older versions of .NET, this was possible by giving an HTML element an id, and write runat="server". Then, one could access the element in the code-behind via its id and manipulate it. How is it done now?
Should I not be able to do the same because of the asp-for tag helper which I used? But how?

Thank you for your help!

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-11-19T23:44:45.14+00:00

    Razor pages (or views) are templates rather than control trees. Just pass a model property and use the value in the template. The onget or onpost will render the the view. Just set a model property to the desired value

    <input asp-for="User.firstname" class="@FirstNameClass" placeholder="First Name">

    0 comments No comments

  2. Anonymous
    2022-11-21T03:08:29.487+00:00

    Hi @mauian ,

    Agree with Bruce, you can create a property in the view page model, then use this property to change the class or other attributes, refer to the following sample code:

    262347-image.png

    [Note]When bind the properties to the html element's attribute, we need to use the @Model.{PropertyName}


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.