.Net MVC Html.Hidden tutorial with examples

In .NET MVC, there are times when we need to store values in the HTML form that are not visible to the user but are required to be sent back to the server when the form is submitted. One way to accomplish this is by using the Html.Hidden helper.

The Html.Hidden helper is used to create a hidden input field in the HTML form. This field is not displayed to the user, but its value can be accessed by the controller when the form is submitted.

Here is an example of how to use Html.Hidden in .NET MVC:

First, create a view with a form that includes a hidden input field:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.HiddenFor(m => m.HiddenValue)
    
}
In this example, MyViewModel is the model that is passed to the view. The Html.HiddenFor helper creates a hidden input field for the HiddenValue property of the model.

Next, create a controller that will receive the form submission:
public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // Get the value of the hidden input field
        var hiddenValue = model.HiddenValue;

        // Do something with the hidden value

        return View(model);
    }
}
In this example, the Index action of the HomeController is used to handle both the GET and POST requests for the view. The HttpGet version returns the view with a new instance of the MyViewModel model. The HttpPost version receives the submitted form data as an instance of the MyViewModel model. The HiddenValue property can be accessed to get the value of the hidden input field.

Html.Hidden Example

@Html.Hidden("myHiddenField")
    

Generated HTML Tag

<input id="myHiddenField" name="myHiddenField" type="hidden" value="" />
    

 

Html.Hidden Set Default Value Example

 

@Html.Hidden("myHiddenField","2")
    

Generated HTML Tag

<input id="myHiddenField" name="myHiddenField" type="hidden" value="2" />
    
In conclusion, the Html.Hidden helper is a useful tool for storing values in an HTML form that are not visible to the user but are required by the server. The hidden input field created by the helper can be accessed in the controller when the form is submitted, allowing you to do whatever processing is necessary with the hidden value.
 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
4 + 7 =
 

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