How to access hiddenField value in asp.net mvc postback controller action?

26,688

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
    ...
}
Share:
26,688
Pradip Bobhate
Author by

Pradip Bobhate

Updated on October 23, 2020

Comments

  • Pradip Bobhate
    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 the hiddenField value in an ASP.NET MVC postback controller action.

  • James Hulse
    James Hulse about 13 years
    Use of the view model should be encouraged rather than the FormCollection from what I understand.
  • David Fox
    David Fox about 13 years
    @havok: modified answer to reinforce view model
  • James Hulse
    James Hulse about 13 years
    Now this is a great answer +1
  • Amir978
    Amir978 almost 10 years
    Thank you for your great solution