Pradip Bobhate
Pradip Bobhate

Reputation: 235

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

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.

Upvotes: 5

Views: 26768

Answers (2)

David Fox
David Fox

Reputation: 10753

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");
}

Upvotes: 18

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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
    ...
}

Upvotes: 4

Related Questions