Reputation: 57
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
Reputation:
To get the name of the controller, you can just use
RouteData.Values["controller"]
Upvotes: 0
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
Reputation: 888213
You should call ControllerContext.RouteContext.GetRequiredString("controller")
Upvotes: 0