Get Route Parameter Value in Controller

Follow
Email

I can't figure out how to obtain the value of a route parameter in a basecontroller.

The url would be http://www.mywebsite.xxx/OceanPines

The route would look like this:

routes.MapRoute(
"HomePage","{Forum}",
new { controller = "Home", action = "Index", Forum= "OceanPines"}
);

I'm new to mvc and apparently a request.params won't work. This is probably something simple and basic but how can I obtain the value of a route parameter in my basecontroller.

Here's some code from the basecontroller with problem marked:

public BaseController(IUserRepository Urepository)

{

_Urepository = Urepository;

string Forum = Request.Params["Forum"]; <<<<HERE IS MY PROBLEM....need mvc equivalent for request.params["Forum"]. The code works if I just use (string Forum = "OceanPines";)

ForumSet.GetForumSettings(Forum); <<<<< Here's where I need to use the variable string Forum

ViewData[
"SysopEmail"] = ForumSet.SysopEmail;

ViewData["Forum"] = ForumSet.Forum;

etc, etc

0
Reply JoeReynolds 2/18/2009 6:10:20 AM
asp.net.mvc 4300 articles. 0 followers. Follow

17 Replies
211 Views

Similar Articles

[PageSpeed] 1

 I believe you're looking for the RouteData. From the controller you should be able to access it like so:

 
string CurrentController = (string)this.RouteData.Values["controller"];
string CurrentAction = (string)this.RouteData.Values["action"];
  
0
Reply unsprung 2/18/2009 6:58:49 AM

Thanks. Almost there, I think.

string Forum = (string)this.RouteData.Values["Forum"];

returns the proper parameter value when placed in the Home controller, however it produces an error of "System.NullReferenceException: Object reference not set to an instance of an object." when placed in the BASEcontroller.

Since string Forum = "OceanPines" works in the BASEcontroller, there must be some issue with using RouteData in the BASEcontroller.  Any ideas?

I'm using the BASEController to set a bunch of site-wide values regardless of the controller called. Works fine except this one snag. My only alternative would be to put a great deal of code in every controller and I don't want to do that.

0
Reply JoeReynolds 2/18/2009 8:22:31 AM

Where are you using this code? RouteData property is accessible after Controller's Initialize method call (that is called from Execute method).
This code could be placed i.e. in overrided Initialize or OnActionExecuting method of your base controller.

If you have a lot of code that is shared between controllers and/or action methods then action filters could be interesting for you: http://www.asp.net/learn/mvc/tutorial-14-cs.aspx


Don't forget to click "Mark as Answer" on the post that helped you.
0
Reply Augi 2/18/2009 8:35:53 AM

Augi, Thanks for tip on action filters. I'll take a look and see if I can solve the problem. Meantime it would be nice to know how/if

 string Forum = (string)this.RouteData.Values["Forum"];

can be used in a BaseController since I have all the other code working via the basecontroller.

I think my original post indicated where I was using the code.

0
Reply JoeReynolds 2/18/2009 9:00:01 AM

 

RouteData.Values[key]

弃我去者,昨日之日不可留。 乱我心者,今日之日多烦忧。
0
Reply chsword 2/18/2009 9:32:35 AM

Hello,.

Augi has already pointed out the problem. Request comes from the controllercontext which is only initiliazed in the Initialize method. Here's a resume of what's going on when you use the Controller base class:

* the constructor gets called

* the Execute method is called

the execute method ends up calling the Initialize method (responsible for setting up the current controllercontext) and then it delegates to the executecore method which ends up doing all the work  needed for running filters and action methods. That's why you're getting null on the constructor.

So, you can override the initiliazemethod and perform the initialization you're doing on the constructor on that override (don't forget to call the base method before putting your initialization logic)


--
Regards,
Luis Abreu
email: labreu_at_gmail.com
EN blog:http://msmvps.com/blogs/luisabreu
0
Reply Luis 2/18/2009 9:53:33 AM

I was just looking at the source code, and the Basecontroller does not expose a RouteData property but it directly exposes its' ControllerContext which is what contains the RouteData.

This might work from the basecontroller:

 
string Forum = (string)this.ControllerContext.RouteData.Values["Forum"];
 

 

0
Reply unsprung 2/18/2009 10:24:20 AM

hello again.

No, it will not work if you call if frmo the constructor. Request is defined on the Controller class which is what you're using as base if you're using the default MVC infraestructure, so you can call Request from your code. the problem is that this info is only available on the Execute method (see my previous post)


--
Regards,
Luis Abreu
email: labreu_at_gmail.com
EN blog:http://msmvps.com/blogs/luisabreu
0
Reply Luis 2/18/2009 10:30:20 AM

unsprung: I think that Joe is inheriting own base controller from System.Web.Mvc.Controller, not System.Web.Mvc.ControllerBase. When he would use ControllerBase then he would get compilation error...


Don't forget to click "Mark as Answer" on the post that helped you.
0
Reply Augi 2/18/2009 10:35:14 AM

 Sorry Luis, I actually started my post before your post existed so I didn't see it. You are completely correct that it won't work before the Execute method is called.

 @ Augi: Also makes sense. I'll shut up now and leave it to the professionals Big Smile

0
Reply unsprung 2/18/2009 10:39:40 AM

 

well, if he mentioned that, I didn't see it :)
--
Regards,
Luis Abreu
email: labreu_at_gmail.com
EN blog:http://msmvps.com/blogs/luisabreu
0
Reply Luis 2/18/2009 10:55:01 AM

I REALLY appreciate the input from everyone. Thanks, and I apologize for perhaps not fully understanding the advice. I'm converting a VB legacy web form application to MVC and C#, and this is my first try at MVC and C#.

Anyway, perhaps the BaseController code below will clearly highlight the problem I am having:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using forumsx;

namespace forums.Controllers
{
 public abstract class BaseController : Controller
    {
        public BaseController()
     { 
        string Forum = "OceanPines"; // THIS WORKS
    //string Forum = (string)this.ControllerContext.RouteData.Values["Forum"]; //  THIS FAILS with
   // error of System.NullReferenceException: Object reference not set to an instance of an object
. I'm trying
//     to get the
Route parameter value of {Forum}
            forumsettings ForumSet = new forumsettings();
            ForumSet.GetForumSettings(Forum);
            ViewData["SysopEmail"] = ForumSet.SysopEmail;
            ViewData["Forum"] = ForumSet.Forum;
            ViewData["ForumID"] = ForumSet.ForumID;
            int ForumID = ForumSet.ForumID;
            ForumSet = null;
 }

} //end class
} // end namespace

0
Reply JoeReynolds 2/18/2009 6:48:21 PM
public abstract class BaseController : Controller
{
    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        string Forum = (string)this.ControllerContext.RouteData.Values["Forum"];
        forumsettings ForumSet = new forumsettings();
        ForumSet.GetForumSettings(Forum);
        ViewData["SysopEmail"] = ForumSet.SysopEmail;
        ViewData["Forum"] = ForumSet.Forum;
        ViewData["ForumID"] = ForumSet.ForumID;
        int ForumID = ForumSet.ForumID;
        ForumSet = null;
    }
}

Don't forget to click "Mark as Answer" on the post that helped you.
0
Reply Augi 2/18/2009 7:33:19 PM

Augi, looks like that did it. Thanks so much.

0
Reply JoeReynolds 2/18/2009 7:43:07 PM

To followup, here's my complete BaseController code. It allows me to grab data in a couple of ways. Perhaps it will help someone else.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Mvc.Ajax;
using forums.Models.Users;
using forums.Models.Articles;
using forums.Models.Images;
using forumsx;


namespace forums.Controllers
{
    public abstract class BaseController : Controller
    {
        private UserRepository _udataContext = new UserRepository();

        public UserRepository uDataContext
        {
            get { return _udataContext; }
        }
        private ImagesRepository _idataContext = new ImagesRepository();

        public ImagesRepository iDataContext
        {
            get { return _idataContext; }
        }

        protected IUserRepository _Urepository;
        protected IArticleRepository _Arepository;
        protected IImagesRepository _Irepository;

        public BaseController() : this(new UserRepository()) { }


        public BaseController(IUserRepository Urepository)
        { }
        protected override void Initialize(RequestContext requestContext) // Augi's solution help
        {
            base.Initialize(requestContext);
            string Forum = (string)this.ControllerContext.RouteData.Values["Forum"];
// Below gets data from class
            forumsettings ForumSet = new forumsettings();
            ForumSet.GetForumSettings(Forum);
            ViewData["SysopEmail"] = ForumSet.SysopEmail;
            ViewData["Forum"] = ForumSet.Forum;
            ViewData["ForumID"] = ForumSet.ForumID;
            int ForumID = ForumSet.ForumID;
            Session["ForumID" + Forum] = System.Convert.ToString(ForumID);
           
            ForumSet = null;

// Below gets data from user controller
            ViewData["UserNameInfo"] = uDataContext.GetOneUser(3).u1Name;
        }
        public BaseController(IArticleRepository Arepository)
        {
            _Arepository = Arepository;
        }

        public BaseController(IImagesRepository Irepository)
        {
            _Irepository = Irepository;

// Below gets data from images controller

            ViewData["ImageID"] = iDataContext.GetOneImage(3).ArticleCode;
        }

    } //end class
} // end namespace

0
Reply JoeReynolds 2/18/2009 8:31:41 PM

hello.

hum...i'm not following your code. you have a constructor which receives a IUserRepository and doesn't pass it to the private field? You have several controllers which receive different repositories and don't call each other to perform initialization. Are you sure this is a good base controller?


--
Regards,
Luis Abreu
email: labreu_at_gmail.com
EN blog:http://msmvps.com/blogs/luisabreu
0
Reply Luis 2/18/2009 10:02:19 PM

Luis, am I sure it is a good base controller? Well... being new to all this I cannot say with certainity.

The code certainly appears to work and do what I wanted.. All the variables returned via the forumsx function are available in my master page and every content page regardless of the controller called after the basecontroller.

0
Reply JoeReynolds 2/19/2009 5:15:31 AM
Follow
Email
Reply:
Similar Artilces:

Get controller and parameter value
 Hi,How do I get the controller and parameter value and pass it on my class?Get the values like below (in Bold).         'page/2/        routes.MapRoute( _           "Paging", _           "page/{page}", _           New With {.controller = "Home", .action = "Index"}, _           ...

How do I get get values of controls inside datalist?
How do I get values of controls inside datalist?   For example, if I have a label inside header template or item template or footer template? Is there anyway to change property of label or any other controls inside those template as well? I would really appreciate if anybody can just post a sample code or a helpful link about datalist? Would really like to know more about the events fired for datalist, itembound, itemcreating etc?   hey there,I used this page to work out how to use datalists http://www.eggheadcafe.com/tutorials/aspnet/d89d1d96-03f1-4784-bbb2-a3db1af...

Help getting control name and value of dynamic controls
I have an application which creates a dynamic form consisting of an html table with web controls in the page. I need a user to be able to fill in this form and then grab the values of each control and save both the control name and the control value to a database. This is the Code that I have Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If not ispostback then Dim infotable As New Table Dim objparticipant As New Participants.ParticipantInfo Dim objCustomFields As New CustomFieldController Dim TypeId As Intege...

How get value from a dynamically created control in a user control
HI, I am working with a version of IBuySpy. On one page is a form that contains a user control that lists the items the user purchased, the subtotal, shipping, etc. I wanted to add a DropDownList from which the user could select the shipper. The dropdown list works fine as long as it has .AutoPostBack = false. However, I cannot figure out how to get the value that the user selected when they finally press the submit button on the form. All attempts to locate the control and it's value have failed. I tried drillingdown from the form to the child controls, and sub child controls. N...

Update parameters and Control parameters: how do you set a default value
I have a Db update that I want to set the lastupdate column to be the date & time of right now.  Can anyone tell me who I can do that in a ControlParameter using the Default value?  Or is there another way it is done when adding parameters to the UpdateParameters tag?  Thanks for the help!!   Don't use a parameter.  Use GetDate() in your SQL (or Now() if using Access)Regards Mike [MVP - ASP/ASP.NET]My site...

Setting the Parameter Value to the Property Value of a Web Control
I want to filter my DetailsView with a declarative parameter. In my case, I am setting the SqlDataSource's parameter values based on the value of 2 TextBox controls on the page. I have a SP that does a SELECT based on 1 of the parameters passed in (either an ID or phone number). Param Name          Value MemberID          TextBox1.Text Phone               TextBox2.Text I want to assign a default value of 'null' for b...

ObjectDataSource.SelectParameters
Hi All, I'm doing my custom paging control and I'd like to get exact parameter value of ODS, but this property is as not public. Is it possible to get this value not using reflection??? Many thanks Andrey labadiena: Hi All, I'm doing my custom paging control and I'd like to get exact parameter value of ODS, but this property is as not public. Is it possible to get this value not using reflection??? Many thanks Andrey In my opinion, I think it can't be done. But I suggest you also to ask this question in .NET Languages where you may get a better answer. Than...

Getting value from a textbox control that was filled with a value from javascript
 I have a textbox control (seen below txtMileageDollars1) that gets filled with javascript based on the number of miles a user types into another textbox (txtMileageMiles1) control.  When I post back with the submit button, the value is blank.  I've tried setting EnableViewState to false, but still cannot get a value on postback.  Does anyone have a solution?   Miles<asp:TextBox ID="txtMileageMiles1" runat="server" Width="50px"></asp:TextBox>   Total (txtMileageMiles1 * rate with javascript)<asp:TextBox...

How to get the value hidden control of user control in .aspx page
How to get the value hidden control of user control in .aspx page   Thanks srinivas  If its a server control (runat attribute = server) and its markup starts with <asp:HiddenField ID="HiddenField1">, you can just call HiddenField1.Value to get the value stored in it. Even if your hidden field is not a standard asp.net control you can still retrieve the value provided the runat attribute is set to server.Hope this helps programming blog Use <%=testhid.ClientId%>For example getting a reference to the object would look like:var testid = document...

can I get value from Web.config and use the value as a parameter?
in my orginal program code        internal static void QueryForExportAgent(ref StringBuilder sb,decimal MasterKey)     {      sb.Append("SELECT * FROM ZT_Detail WHERE ");      sb.Append(fMasterKey);      sb.Append("=");      sb.Append(setParametersValidation(MasterKey));      sb.Append(" AND ");      sb.Append(fTYPE);  ...

Unable to get values of a bounded control when postingback, How do I get previous state?
the second DDL doesn't work, cuz the items are refilled in the postback event.and of course if I fill in the items only if Not Page.IsPostBack, it doesn't fill anything. however, how can I get the previous DropDownList2 instantiated control, I mean I want to get the control as it would be looking before the user changed index + new selected index as an argument. or else - maybe I have to do it completely in a different way (?).  <%@ Page Language="VB" %> <%@ Import Namespace="System.Linq" %> <!DOCTYPE html PUBLIC "-//W3C/...

Get user input from dynamic created control, why i cant get the value???
Hi!, i was tried to dynamically generate some textboxes according the selected number in a dropdownlist, but when i need to get the user input from those textboxes.. i cant get at all!!, Can any1 guide me on tis? Below is my code.Basically, i have 1 dropdownlist (ddltbCount), 1 placeHolder(Pholder1), 1 button(btGetValue), i dont know y i cant post the html here... Private count As Integer = 1 Sub IterateThroughChildren(ByVal parent As Control) For Each c As Control In parent.Controls If c.GetType.ToString.Equals("System.Web.UI.WebControls.TextBox") AndAlso c.ID Is Nothing Then ' CType(c, T...

how to get the ID and Value of Controls inside the ASP.NEt table Control
hi       I have a asp.net table ctrl in my page, and im loading textbox,drpbox,chkbox dynamically on that table on the page load.In the button click  i need to get all the dynamically added controls ID and value of the controls .Please help me.........   ThanksThanks, table doesn't allow this.if you can use gridview instead. سیستم آموزش مجازیسیستم مدیریت کتابخانه دیجیتالوستاگزارش ساز Hi,  TableRow tr1 = (TableRow)((Table)tdSkills.FindControl("tableSkills")).FindControl("tr1Skills"); TableCell tc1 = ((TableCell)t...

Getting value of a property in Parent User control from a Child user control
I have a ChildUserControl that is loaded inside a ParentUserControl. The host page loads ParentUserControl.I would need to access properties in ParentUserControl from the ChildUserControl.Thanks for your time Here's some ideas: You can from the child access the parent and run findcontrol. child.parent.findcontroL("indyanguy1") child.parent.parent.findcontrol("indyanguy1") The trick is when you get your findcontrol working to cast the result to the object type your looking forHere I'm looking for a label so I cast to label then I can use the .Text property.Y...

Dynamically Loading User Control and Maintaining its viewstate. And Getting Values from the control.
 I have a drop down which is populated on the page looad.  When i select an item from drop downlist i get to see two listboxes with add/removing the objects from one left to right listbox and below that i have a user control which should be populated dynamically based on the selectedvalue from drop down list.  So there are three sections that are seen once a selected value is consiedered from drop down list.  Now I am getting the user control using the below code givencase "42": viewRequired = "vw_AncCostSavingsByCarrier_adhoc";    ...

How to get return value or output value from stored procedure with sqldatasource control?
I created a user registration web page with sqldatasource, some textbox controls or submit button web control, I applied below stored procedure in insert command of sqldatasource control, but how can I get return value from stored procedure after clicking submit button, I want to judge whether data has been saved into database by return value, then give user a message. Who can tell me? thanks much. ALTER PROCEDURE UserInsert ( @Email nvarchar(50), @Password nvarchar(50), @FullName nvarchar(50), @Phone nvarchar(50), @Mobile nvarchar(50), @Address nvarchar(100), ...

how get the values of a parameter?
Thank you very much in advance for your help. I'm new using ReportingServices and now I'm making a Windows app to manipulate reports. When a report has parameters, some of them has a default value but no others. My question is... How can I retrieve the values of a parameter using ReportingService class? I can read the content of a folder, also can read the parameter(s) of a report, can read default values too, can create the report if the app pass a valid value to a specific parameter, but I'm stuck trying to get the values for a parameter that has not default value.Roberto Perez...

get parameter values
hi, I have a crystal report with pre-defined parameter which is shown as a dropdownlist (with multiple values). With the use of Crystal Report Viewer in .NET, how can I get the parameter values in coding when I load the report. any advices is appreciated bryan I'm trying to do something like that. The thing is that I don't know how to pass the value to the report. I don't even know if it's possible. I think there has to be a way. I want the user to input a value in one of the form's textboxes and I want to get that value and use it in the report, but when I try to I get th...

Getting Values from other Controls...
If you have a control yo u developed...and yuou need to get the value of another controls id on the same page...how would you go about doing that exactly? I tried with id.property, but of course that didnt work. so again.. my control code is in a codebehind....and i want to add a function that does something, but that function needs to get info from another control on the page, but im not sure how to do it. thx in advance. "Only when we are no longer afraid do we begin to live" -D. Thompson // f bush. ----------- "No man succeeds without a ...

Controls not getting value
Hello, I am loading usercontrols dynamically and the values are populated in the user control. I have a button that when click adds the usercontrol The usercontrol is being added, but the values are not populated. Any Ideas? int AddThisNumberOfControls = NumberOfControls; while(AddThisNumberOfControls>0){ // Create the Category Selector Control Catlist CatSelector = (Catlist)LoadControl("components/Catlist.ascx"); CatSelector.CatHeadingNumber = "Category " + AddThisNumberOfControls; this._ph_Cat...

get parameter values
I am trying to get a parameter from http request which has more than one value. For example, the url is http://localhost/getParam.aspx?State=FL&State=TX&State=MD, I want to get a string list like ("FL", "TX", "MD"). The parameter could be sent through a post form. In Java, there is a function - requst.getParameterValues. Is there any such funciton in ASP.Net (VB) ?  Huaichen wrote:I am trying to get a parameter from http request which has more than one value. For example, the url is http://localhost/getParam.aspx?State=FL&State=TX&State=MD, I want to get a st...

FileUpload control value gets clear when another control uses Ajax to retrieve data
Hello all, I have a web form.  There is a DropDownList control inside an update panel and the content is updated when a RadioButtonList control fires SelecteIndexChanged.  I also have another control, a FileUpload control.  If you select a file for the file upload control and then change the value RadionButtonList list control, the selected file in the FileUpload control disappears.How do I prevent RadioButtonList from clearing the value of the FileUpload control?Any help will greatly appreciated,  TIA,Dawa Below is the code: 1 <asp:RadioButtonList ID=&quo...

Issue with getting values from child controls in a gridview, to use for the update using a SQLDataSource control
Hi all, I have a gridview bound with a SQLDataSource. I am using the Update feature of the SQLDataSource to update a SQL Server database with values entered into the gridview. However I am not getting it to work. I believe this is due to the controls that contain the user entries are not the gridview itself, but rather child controls within the gridview. I have been using the names of the actual controls but nothing happens. Upon submit, the screen returns blank, and the database is not updated. Here is some code:   <asp:GridView ID="GridEditSettlement" runat="server" AutoGenerate...

Exception "Specified value has invalid Control characters." with querystring parameter value €€€
Hi There, I have created a very simple new WCF Webservice: HelloWorldService. In a new page "wcf.aspx" I use json to create a proxy to the webservice: <script src="HelloWorldService.svc/js" type="text/javascript"></script> When I request the page "wcf.aspx" and execute webservicemethod HelloWorld, it works normal. BUT: when I request "wcf.aspx?test=€€€" I get the following exceptions:- <ExceptionType>System.ArgumentException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089&...