Saturday, March 25, 2023

How to set value in a input hidden field by using model class in ASP.NET MVC?

You can do it by using your model class property into hidden field.


Step1: Include your model class in your cshtml view page

@model <YourApplicationName>.Models.<YourModelClassName>

Step2: By using model class property set it to value attribute of your hidden field

<input type="hidden" value="@Model.<YourModelClassPropertyName>" />

Demo:

Step1: Let's suppose we have a model class "Product" with some properties as given below:


Step2: Now, we have to pass our model class object to it's view page. We can pass it from an action method which will be available in a controller class. Here in this example, I'm creating a Product class object in HomeController's Index method and passing it to view page.


Step3: Now we have to access this class object on our view page. For that we can give a reference of our model class at the top of view page. Also, by using model class property, we are setting the ProductId of the referenced object into hidden field's value attribute.


Step4: 
Now we can see the output. The referenced object's ProductId is visible in input field when we checked by inspecting element in browser.


No comments:

Post a Comment

Will it be possible to live on Mars, as Elon Musk has said?

Elon Musk has expressed his ambition to establish a human presence on Mars in the future. While living on Mars is a long-term goal for Space...