Can we access the asp:Label
value directly in an MVC postback controller action? I would also like to know how to access the hiddenField
value in an ASP.NET MVC postback controller action.
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");
}
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
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With