How to access hiddenField value in asp.net mvc postback controller action?
Solution 1
In ASP.NET MVC, you don't use <asp:...
tags, but you could try POSTing any number of inputs within a form to a controller action where a CustomViewModel
class could bind to the data and let you manipulate it further.
public class CustomViewModel
{
public string textbox1 { get; set; }
public int textbox2 { get; set; }
public string hidden1 { get; set; }
}
For example, if you were using Razor syntax in MVC 3, your View could look like:
@using (Html.BeginForm())
{
Name:
<input type="text" name="textbox1" />
Age:
<input type="text" name="textbox2" />
<input type="hidden" name="hidden1" value="hidden text" />
<input type="submit" value="Submit" />
}
Then in your controller action which automagically binds this data to your ViewModel class, let's say it's called Save, could look like:
[HttpPost]
public ActionResult Save(CustomViewModel vm)
{
string name = vm.textbox1;
int age = vm.textbox2;
string hiddenText = vm.hidden1;
// do something useful with this data
return View("ModelSaved");
}
Solution 2
In ASP.NET MVC server side controls such as asp:Label
should never be used because they rely on ViewState and PostBack which are notions that no longer exist in ASP.NET MVC. So you could use HTML helpers to generate input fields. For example:
<% using (Html.BeginForm()) { %>
<%= Html.LabelFor(x => x.Foo)
<%= Html.HiddenFor(x => x.Foo)
<input type="submit" value="OK" />
<% } %>
and have a controller action which would receive the post:
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
// model.Foo will contain the hidden field value here
...
}
Pradip Bobhate
Updated on October 23, 2020Comments
-
Pradip Bobhate over 3 years
Can we access the
asp:Label
value directly in an MVC postback controller action? I would also like to know how to access thehiddenField
value in an ASP.NET MVC postback controller action. -
James Hulse about 13 yearsUse of the view model should be encouraged rather than the FormCollection from what I understand.
-
David Fox about 13 years@havok: modified answer to reinforce view model
-
James Hulse about 13 yearsNow this is a great answer +1
-
Amir978 almost 10 yearsThank you for your great solution