nilesh1foru
nilesh1foru

Reputation: 57

How to get controller name in another class?

I am developing MVC application.

I want to pass controller to some other class for validation purpose. After passing the controller, I am unable to get the controller name in that class.

  [HttpPost]
    public ActionResult Create(Location location)
    {
        if (ModelState.IsValid)
        {
            Validations v = new Validations();

            boolean b;


            //passing controller in another class's method
           b = v.ValidProperty(location);


           if (ValidProperties == true)
             {
                 db.Locations.Add(location);
                 db.SaveChanges();
                 return RedirectToAction("Index");

             }

        }


    }

Getting controller in below method

 public void  ValidProperty(object Controller)
    {

    //Gives an error in below line
        string CtrName = (string)Controller.ToString;

     }

How to get the controller Name ?

Upvotes: 1

Views: 611

Answers (3)

user981508
user981508

Reputation:

To get the name of the controller, you can just use

RouteData.Values["controller"]

Upvotes: 0

HaBo
HaBo

Reputation: 14327

b = v.ValidProperty(ControllerContext);

you may be wondering where am I initializing ControllerContext variable. well you don't have to

     public void  ValidProperty(ControllerContext ControllerContext)
        {
           // do your logic here.
    }

Upvotes: 2

SLaks
SLaks

Reputation: 888213

You should call ControllerContext.RouteContext.GetRequiredString("controller")

Upvotes: 0

Related Questions