Get Route Parameter Value in Controller

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
JoeReynolds
2/18/2009 6:10:20 AM
asp.net.mvc 4300 articles. 0 followers. Follow

17 Replies
399 Views

Similar Articles

[PageSpeed] 14

 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
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
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
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
JoeReynolds
2/18/2009 9:00:01 AM

 

RouteData.Values[key]

弃我去者,昨日之日不可留。 乱我心者,今日之日多烦忧。
0
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
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
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
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
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
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
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
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
Augi
2/18/2009 7:33:19 PM

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

0
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
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
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
JoeReynolds
2/19/2009 5:15:31 AM
Reply:
Similar Artilces:

How do I get ASP to clear cache?
Hi There, I'm an ASP newbie, and no very little however, I wondered if you could help me out. I'm currently using an 'asp' script to create a bunch of session variables, by passing the Windows Username/ Password, when the user logs on, into coldfusion. I'm then using this to restrict people to certain areas. I've done this to minimize upkeep of usernames and passwords. When I log out, a coldfusion page sets the session variable to false. However, the browser seems to keep the user logged in even when I log out and shut down all windows. Do you know of a way to stop this caching,...

How to use stylesheets in user controls(.ascx)
Hi all, I am developing user control in .NET 2.0. User controls (*.ascx) doesn't have html/header section to keep stylesheet(css) files. so in this case how do i use styles in user controls(*.ascx) . Please provide me solutions, Thanks in advance.Madhu.G  Set the cssclass to the stylesheet name (css file) .. Remember the user control will always be part of the page so if the page has a stylesheet directive it will automatically apply to the user controlHaissam Abdul MalakMCAD.NET| Blog | I give you some links on how to use css in web controls.http://www.webxact.co...

Get a handle of the controls of Parent page from iframe child pages
What I'm trying to do is enable a tab from the tabstrip on the parent page after a user hits an imagemap that is on another tab on the parent page. But the contents of the tabs are sitting in seperate pages that are linked with iframe control. The contents in other words are in child.aspx pages.    How can I have a handle over teh tabstrip and change the seleted tab. If I try to go back from the server side, with parent.   The child.aspx page doenst recongnize the parent control. This is the parent page that has the list of tabs <ComponentArt:TabStrip id=&q...

Maximum characters that can be used in the "message" parameter of xp_sendmail
Hello, I am using xp_sendmail to send email to our supervisors containing a report on which sites have not synchronised with our head office database in the last 48 hours so that they can take a certain action. I am dynamically build the "message" argument of xp_sendmail as follows. Sample code : declare @header varchar(2048) declare @main_message varchar(4096) declare @footer varchar(2048) declare @disclaimer varchar(2048) declare @full_message varchar(8192) select @header='The following sites have not synchronised in the last 48 hours : \x0A\x0A ' ...

Controlling the order of columns in a table
When I drag-drop a reference from table B to table A, PD adds columns to table B. These columns land in the middle of the table's list of columns. Then, when I try to alter database, the script does drop/create table when I wanted an alter statement. I want all new columns to land in the bottom of the table's column list. How can I do that? I'm using PD 8.01 You need to manually move the columns down to the bottom of the list in the Table Properties dialog box, Columns tab. Highlight any/all columns and use the arrow buttons in the lower/left of the grid to move them...

Get "EXECUTE permission denied on object 'sp_sdidebug', database 'master', owner 'dbo'." error when debugger attached
I'm connecting to database using VPN. When i execute web site WITHOUT attching debugger in visual studio, it connects to database fine and get the expected result. BUT if i attach debugger to aspnet_wp.exe in visual studio, i get following error when i try to open sql connection. "EXECUTE permission denied on object 'sp_sdidebug', database 'master', owner 'dbo'."   why and how do i resolve this problem Hi,You have not grant the execute permission for that stored procedure sp_sdidebug. Give execute permission and it should work.Hope this helps.&...

adding login to the control panel in DNN2 Beta
Would it be possible to add the login boxes inside the Control Panel and have it visible all the time? If that is not possible then could i atleast add it to the navigation pane under the control box and have it permantely visible? Thanx newbie nuker Not sure what you mean by Control Panel, but you can create a skin that references the Signin.ascx control directly so that it shows on all tabs.John M. ...

Database getting corrupted...
We developed an application using PB 5.0.03 and Sql AnyWhere 5.0 (authenticated version). The application was installed on a lap-top computer with a standalone database engine. Works fine. Customer left the application & database running over the weekend. It was working fine when she left the computer for the weekend but started giving them assertion failed (No. 50213) when she tried to work on the application the following Monday. We translated the .LOG file and found out that the database was doing checkpoint maintenance every half hour till Monday morning and there are no d...

DW Control Upstages VSB Control
I've got a master-detail window (using pfc u_dw descendants) with a vertical scrollbar. No matter what I do, one of the dw's insists on being in front of the vsb. I've tried "Send_to_back" in the painter and I've tried dw_detail.setposition(behind!, vsb_1) in various events (dw constructor, dw resize, vsb resize, w postopen.) Nothing seems to put this dw in its place! Has anyone ever seen this kind of window position problem? What am I missing? TIA ...

Syntax error: wrong number of values for INSERT
Hi all 1.I insert row 2.Input data all column 3. Update and error Syntax error: wrong number of values for INSERT I think that the error speaks for itself. Check to ensure that you have not added/omited any columns in the datawindow. If that shows nothing, run a PB Database trace and check the call being made. Is is correct and as expected? Post you results if you continue to have problems. /ck "Soopsawat Arakputtananta" <powerpig@aroma.com> wrote in message news:3c704855.5026297@forums.sybase.com... > Hi all > 1.I insert row > 2.Input d...

HtmlAnchor server control link doesn't work! pls help!
Hi, there, i am new to .net 2005. Now i am using beta 1.I want put a HtmlAnchor in my datagrid, <asp:TemplateColumn HeaderText="Authorization "><itemtemplate><a style="color:black;" runat="server" onserverclick="auth_click" href="Project.aspx?ProjectID=<%#DataBinder.Eval(Container.DataItem, "ProjectID")%>'>Accept</a></ItemTemplate></asp:TemplateColumn>In the code behind, I just want to get the link text which I just clicked, here is "Accept", then I wrote: Sub auth_click(ByVal sender As Object, ByVal e As EventArgs)   Sess...

GW 8.0.1 client tries to go to internet to get .net?
I'm noticing on my event viewer logs, that when I try to install the 8.0.1 client on Windows XP, it appears to try to go to MS download site to grab some .net files Is this normal? It fails on that attempt, shows an error in the event viewer, and then appears to continue to install. (since our machines have .NET 2.0 on them) However, if a machine does not have .NET 2.0 the whole install just disappears (no errors whatsoever). -- kjhurni ------------------------------------------------------------------------ kjhurni, It appears that in the past few days yo...

POST GET GET GET GET... WTH?
Hi, I'm at a loss to explain this... I have an ASPX page that I can't always navigate to. When I developed the app (it's Starter Kit Portal-based), I did it on my LAN and have had no trouble accessing the page. However, upon deployment, I see the following behavior: 1. POST request goes out looking for MyForm.aspx 2. GET request for MyForm.aspx 3. GET request for MyForm.aspx 4. ... X. GET request Sometimes, the page finally loads. Other times, it just ends up blank. Many times, it doesn't load at ALL the first POST - I just get a "The pa...

Problem getting records from access db
Hi Iam using vs2003 and an access db on a website I am working on. I am trying to get the random top 2 items to display as feature items.If I run the query in access it works fine but in vs it alswyas comes up with an nullexception error.code is belowThe datalist<asp:datalist id="rptfeature" repeatcolumns="2" width="100%" border="0" cellspacing="0" cellpadding="0" runat="server"> <itemTemplate> <center><a href='product.aspx?id=<%# Container.Dataitem("OSProducts.ProductID") %>&#...

Why did not get UserID?
I used the code bellow try to get UserID but only gave me ASPNET account. Dim UserFullNTID As String = System.Security.Principal.WindowsIdentity.GetCurrent.Name I got ASPNET in all computer no matter who is loging. How to get different User ID in computer based on who is login? Try User.Identity.Name Regards Fredr!k I got it! Thank you. One more question, how do you get what NT user's group belong to? Just cast the Identity to a WindowsIdentity, like: ((WindowsIdentity)User.Identity).Name Regards Fredr!k No, it did not work this time! What happen...

How to run a loop and get all data from table? (thank you)
I am planning to read all all data of columns from 1 table if my table data is like below : type_no | name_title | name_eng | name_cht | text_content_eng | text_content_cht|--------------------------------------------------------------------------------    2   | shopping   |    A     |     AA   | Hi how are you?  |   xxxxxxxxxxxxx |---------------------------------------------------------------------------------    2   | shopping   | &nb...

Getting Access Denied Error on Framework
Hello, I am probably missing something very basic, but I am getting the following error when trying to use the new .096 build. This is keeping me from being able to do anything else... Server Error in '/blogs' Application. Access to the path "C:\winnt\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files\blogs\70757174\e9b4709e" is denied Running windows 2000 server and the site is of the format: abc.xyz.org/blogs Thanks, Drew Well I fixed the issue. I found a similar issue at the following link. (The server is a domain controller as well). I ran asp...

[Policy Builder] Add attributes to Value element
Hi All, I want to modify the following XML fragment Code: -------------------- <add-attr attr-name="Full Name"> <value type="string">Jean Baptist Theodorus</value> </add-attr> -------------------- so that it will look like the following: Code: -------------------- <add-attr attr-name="Full Name"> <value endDateTime="2037-12-31" startDateTime="2009-07-29" type="string">Jean Baptist Theodorus</value> </add-attr> ----------------...

Why i get error ?
Why this is generate error (end of line) ? EXECUTE IMMEDIATE ('DECLARE kursor CURSOR FOR select '|| @SelectKlucz ||' from '|| @Tabela1 ||' WHERE 1<>1 group by '|| @SelectKlucz ||';'); Fantom Fantom wrote: > Why this is generate error (end of line) ? > > EXECUTE IMMEDIATE ('DECLARE kursor CURSOR FOR select '|| @SelectKlucz ||' > from '|| @Tabela1 ||' WHERE 1<>1 group by '|| @SelectKlucz ||';'); In Watcom SQL, DECLARE statements must occur immediately after the BEGIN statement of a compou...

How can I pass values between 2 usercontrols
Hello everyone I have one webform named index.aspx, on that page I have 2 usercontrols, how can I let one usercontrol pass value to the other. Regards Jón Sveinsson hi jonhsv, It depends on what kind of user controls you have on your page. Can you post the code or tell me what kind of controls they are? gr, Captain Bieluh"0x2B | ~0x2B" , Hamlet...

ajax - calender control
hi all, Many of you know this issue ,i am using  DIV tag s besides i am using the ajax control toolkit calender control, it hides behind the div tag,  i searched many sites no one given solution , they all saying the same problem with ie 6. and moe over IE 6 is not obsolete yet, is there any solution to over come this bug of I.E6 please don't tell to  use Internet Explorer 7.0 or to use the mozilla firefox our project requirement is to fit with in ie6 waiting for your esteemed suggestion Thanks,raj   raj What exacty is your problem with...

get full serverpath
using pb 9 on xp In need to 'translate' pathes that contain network diskdrives to the full serverpath e.g. g:\subdir\file.txt -> \\server\subdir\file.txt f:\file.txt -> \\server\subdir\subdir\file.txt any functions therefore in pb or are there api-calls thanks for help martin > using pb 9 on xp > > In need to 'translate' pathes that contain network diskdrives to the > full serverpath > > e.g. g:\subdir\file.txt -> \\server\subdir\file.txt > f:\file.txt ...

How do I determine at runtime a certain property of a control?
 HelloAm writing a program that demands my knowing one property of a Usercontrol which from my program will make it unique.Say Textbox1.Addvalue- An added property to a textbox.Code Property Addvalue as string..........................end property  How would I know the that this Textbox1 has this property while search through all the controls in a form?By usingFor each cto as control in frm.controlnext Please help in case if there is any other code to use let me know.  You can use reflection technique to know about this Textbox's properties. Hope...

How do you get to get to the NAL debug screen?
I remember a debug screen that you could get to in NAL by doing some function key. I can't remember exactly how it work, could anyone assist? ZFD 4.01 IR4 Thanks , > I remember a debug screen that you could get to in NAL by doing some > function key. I can't remember exactly how it work, could anyone assist? > Help, About, Hold down F2, More - Anders Gustafsson, Engineer, CNE6, ASE NSC Volunteer Sysop Pedago, The Aaland Islands (N60 E20) Novell does not monitor these forums officially. Enhancement requests for all Novell products may be made at h...

getting an occasional "domain not found in db" error
Hi, For some reason I'm getting an error stating that the domain, http://pinkponytailsalon.com, cannot be found in the database. It's wierd because sometimes it works; however, many times I and other people as well are getting this error. We're not getting this error when we use the sub domain pinkponytail.sillysmart.com. When I created this portal I created it as a child portal. I then added the alias pinkponytailsalon.com. I would appreciate any help because the client is becoming impatient. Thank you, Travis Bennington I think this might be related to other posts; see Post 53...