Invoking and Passing Values to Action Programmatically in MVC

Invoke the actions programmatically from view page code behind. This article will be helpful for migrating webistes from 2.0 to MVC

MVC's main objective is to seperate the presentation and bussiness logics, and its also not recommend much code in views.

There may be situation we need to invoke the actions from code behinds of Views. 

Here is the code to invoke Actions of controllers programmatically,

Use the below code in any server side event.. like button click, dropdownlist selected index changed, etc

Response.Redirect(Url.Action("Action Name", "Controller Name"));

here is the eg:

Response.Redirect(Url.Action("Index", "Home"));

Passing Values

When you need to pass the values to your action through code behind,

you can use RouteValueDictionary   class, under System.Web.Routing namesapce

Cosider you have a Controlle with name "Home", and action with Name "Index" as


ActionResult Index(string Id)

       //your logic

you can call the above Action from code behind and pass value for Id as

 RouteValueDictionary rval = new RouteValueDictionary();
  rval.Add("Id", "Value for this");
  Response.Redirect(Url.Action("Index", "Home",rval));

By Vasanthakumar D   Popularity  (2863 Views)