Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
Pradip Bobhate Avatar asked Mar 09 '11 22:03

Pradip Bobhate


2 Answers

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");
}
like image 116
David Fox Avatar answered Oct 05 '22 12:10

David Fox


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
    ...
}
like image 37
Darin Dimitrov Avatar answered Oct 05 '22 12:10

Darin Dimitrov