2

I have a SQL query where I want to pass controller name as one of the where clause compare parameter. And there are many controllers within the application. Depending on the controller name there will be different result of query to be executed. So how can I pass name of the controller to some third controller.

Using this @ViewContext.RouteData.Values["controller"], I can get name of controller but within the view of that controller only. So how can this be achieved in another controller action method.

mipe34
  • 5,596
  • 3
  • 26
  • 38
Krish
  • 43
  • 1
  • 13
  • If I understand it well, you can just pass the name of the controller as the action method parameter. – mipe34 Dec 17 '12 at 11:04
  • I am getting name of controller in say view of Home controller so from this view i want to pass it to say Testcontroller action method. Don't know how can this be achieved? – Krish Dec 17 '12 at 11:24
  • And is your intention to navigate there with some `@Html.ActionLink` or do you want just render the result of action of the `TestController` on the same page with `@Html.RenderAction` ? – mipe34 Dec 17 '12 at 11:45

1 Answers1

1

There are several ways how to pass value to an action method in ASP MVC. It depends on the type of request.

Example for GET request

// navigation to action
@Html.ActionLink("link","myAction","otherCon", new {controllerNamePar = ViewContext.RouteData.Values["controller"]}

// render result of action into current view
@{Html.RenderAction("myAction","otherCon", new {controllerNamePar = ViewContext.RouteData.Values["controller"]}}

controllerNamePar will be sent as the query string in the url.

Example for POST request

@using (Html.BeginForm("MyAction", "OtherCon", FormMethod.Post))
{
    @Html.Hidden("controllerNamePar", ViewContext.RouteData.Values["controller"])
    <input type="submit" value="OK" />
}

controllerNamePar will be sent as the part of html form.

mipe34
  • 5,596
  • 3
  • 26
  • 38
  • The view for TestController doesn't exist. This controller just contains methods called using ajax call and this method returns some records from database. – Krish Dec 17 '12 at 12:55
  • 1
    It does not matter. I only wanted to show you that only way to pass values to an action method is via QueryString or via html form. And you did not provide enough information how are you trying to accomplish your task so I described both options. Could you please expand little bit more your question (show some code you have tried to accomplish your scenario - home view, home controller, other controller). – mipe34 Dec 17 '12 at 13:45