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
661 Views

Similar Articles

[PageSpeed] 9

 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:

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"}, _           ...

Routing, parameters, controllers, and views
Hi guys/girls, I just started playing with MVC yesterday and I have to say I'm very impressed with how easy it is to get going and the clean markup it generates (as opposed to webforms). Here's my scenario, any help will be greatly appreciated.This particular project i'm working with is in vb.net, but I can translate from c# if needed... Basically I want to setup a structure like this "/Groups/{groupname}/" I want it to, based on the logged in user, get a certain group by group name and display the group information on that page. I have groupscontroller.vb set...

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

How to get the HREF value of the Anchor tag in a web page using the web browser control in vb.net
Hi Friends,               i have a webserver control in my application.i load the web browser control on a button click using the below code Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click                AxWebBrowser1.Navigate("http://www.rateitall.com/i-322335-.aspx", False) End sub once the page is loaded in the browser i want the <a> HREF value in that page.For example if that page has ...

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

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

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

Control.Value and Control.SelectedItem.Value
Can someone explain to me the difference between say, Dropdownlist.SelectedItem.Value and Dropdownlist.SelectedValue?? Just curious, Thanks!Tim These are going to return the same thing. dropdownlist.selectedvalue is a shortcut to get the currently selected value in the dropdown. If that is all you want then you can just use that. If you want to access the currently selected item you can use dropdownlist.selecteditem and that return the item and you can then access any of the item's properties, including in this case the value property. If this post answered your question please r...

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);  ...

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

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

Web resources about - Get Route Parameter Value in Controller - asp.net.mvc

Hitachi HD44780 LCD controller - Wikipedia, the free encyclopedia
The device can display ASCII characters, Japanese Kana characters, and some symbols in two 28 character lines. Using an extension driver, the ...

Review: SteelSeries Nimbus is the best gaming controller for Apple TV and iPad
Comfortable, competitively priced and featuring a Lightning port for recharging, the SteelSeries Nimbus is the best iOS-compatible gaming controller ...

Black Friday gaming deals feature $300 consoles, $40 controllers, $1 games
Dell has what's probably the best bundle offer on the Xbox One this Black Friday. The Black Friday sales bonanza (which is now officially bleeding ...

One of the most iconic game controllers is back and better than ever [Deals]
For gamers of a certain age, there are few things as familiar and full of memories as the look and feel of the Super Nintendo controller. Those ...

Controller remapping is now available on all Xbox One controllers
Good news for everyone who owns an Xbox One but didn't shell out for one of those ultra fancy premium Elite controllers, you can now remap the ...

Steam Controller review: Time to put away your PC's mouse and keyboard?
... get their gaming kicks just a few feet from a monitor, huddled over the keyboard with their trusty mouse in tow. But with the new Steam Controller, ...

Steam Controller's new trick is designed for strategy games
By default, the haptic touchpads that define Valve's Steam Controller are just thumb-friendly fill-ins for a proper mouse but that's not all ...

Xbox Elite Wireless Controller
Xbox Elite Wireless Controller

GeekWire Deals: Get your old-school game on with this Bluetooth-enabled SNES controller
Today’s video game controllers are fantastic. They pack vibration feedback motors and a plethora of input options into an ergonomic package. ...

Turning a Car into a Playstation Controller
For a rather obscure brand advertisement, Nissan decided to turn one of their cars into a giant Playstation 4 controller to play a game of football ...

Resources last updated: 12/6/2015 12:40:48 AM