ASP.Net MVC How can I access hiddenfields on controller Index()

29.6k Views Asked by At

I have several views that have a hidden field like this:

<input type="hidden" runat="server" id="hiddenTab" value="1"/>

each view may have a different value.

I have a base controller that I want to be able to access this value on the constructor:

public class BaseController: Controller 
{
    public BaseController() 
    {
        string tabid = Request.Form["hiddenTab"];
    }
    
}

and finally I have several controllers that implement this base controller:

public class HomeController: BaseController 
{
    public ActionResult Index() 
    {
        string tabid = Request.Form["hiddenTab"];

        //if tabid = 1, do this.. if it is 2, do this, etc...
    }
}

How can I access the hiddenfield value or the value of any other control on the view for that matter when the controller is first loading? The application is just starting at this point, so nothing has been posted yet. I have tried to access the value from both the controller and the base controller and the Request.Form has no values in it.

I am converting an application from aspx to MVC and on the aspx app, the masterpage codebehind had this:

HtmlInputHidden hidddentabid;
hidddentabid = (HtmlInputHidden)Body.FindControl("hiddenTab");

This worked fine for a master page in aspx, but not in MVC. I have spent hours looking and can't find anything on this. All I am able to find is how to access hidden values that are POSTED to a controller. Nothing on when a controller for a view is first rendered.

Any help would be greatly appreciated!

5

There are 5 best solutions below

0
On BEST ANSWER

you are missing the name property for the hidden element. you can get the values based on the name. try this

<input type="hidden" id="hiddenTab" name="hiddenTab"  value="1"/>

as Andrie mentioned runat="server" is not required in Asp.Net MVC

0
On

Add parameter to your action, it will be automatically mapped:

public ActionResult Index(int hiddenTab)
{ 
   //Do smth...
}

runat="server" - this attribute is for classic ASPX pages. You don't need this if you are using ASP.NET MVC View Engine.

1
On

Under MVC ASP.NET use the Model, reading your code you are not using the paradigm of MVC! The best way to use MVC is to put propriety in your model, reference your model in the view and in post of your action put that model in the argument of action like

[HttpPost]
public ActionResult Index(Modelpage model){...}

the model

public class Modelpage {
    public int hiddenTab {get;set;}
}

in the view

[...]
@Html.HiddenFor(m=>m.hiddenTab)
[...]
0
On

html controls having name attribute can only be accessed using request.form object and for this, hidden field or whatever control should be in form.

1
On

for accessing any form control in controller action method, firstly check whether the same element is included in form tag or not.