HTML.HiddenFor set value in Asp.Net MVC

In ASP.NET MVC, the Html.HiddenFor helper is commonly used to create hidden input fields in a form. These fields allow you to store values on the client side, which can be useful for passing information between the server and the client without displaying it on the page. Below is a step-by-step guide on how to set a value for Html.HiddenFor in ASP.NET MVC.

1. Create a Model

  • Define a model class with the property for which you want to create a hidden field.
public class YourModel
{
    public int YourProperty { get; set; }
}

2. Initialize Model in Controller

  • Initialize an instance of your model in the controller action and set the desired value.
public class YourController : Controller
{
    public ActionResult YourAction()
    {
        YourModel model = new YourModel
        {
            YourProperty = 123 // Set your desired value here
        };

        return View(model);
    }
}

3. Use Html.HiddenFor in View

  • In your view, use the Html.HiddenFor helper to create a hidden input field.
@model YourNamespace.YourModel

@using (Html.BeginForm("YourAction", "YourController", FormMethod.Post))
{
    @Html.HiddenFor(model => model.YourProperty)
    <!-- Other form elements go here -->
    <input type="submit" value="Submit" />
}

4. Retrieve Value in Controller

  • When the form is submitted, retrieve the value in the controller action.
[HttpPost]
public ActionResult YourAction(YourModel model)
{
    int yourValue = model.YourProperty;
    // Process the value as needed
    return View(model);
}

Conclusion

Setting a value for Html.HiddenFor in ASP.NET MVC involves initializing the model in the controller, setting the desired value, using the Html.HiddenFor helper in the view, and retrieving the value in the controller action when the form is submitted. This approach helps in maintaining state between the client and server without exposing the data on the UI.

 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
6 + 7 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice