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
See related articles to this posting

 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
asp.net.mvc 4300 articles. 0 followers. Follow

17 Replies
52 Views

Similar Articles

[PageSpeed] 37

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