views:

188

answers:

1

Hello,

I have some problems on passing an id from URL into my controller action

Lets say I have this Url : Bing/Index/4

In my master page I would like to generate a form that submits to BingController SearchAction. I did something like this

using(Html.BeginForm<BingController>(action => action.Search(id)))

How to get id (4 in this example) from url to pass it to the Search action ?

Thanks for your help

+3  A: 

To access that data in a master page, your controllers would need to add it to the ViewData so the master page has access to it.

public ActionResults Index(string id)
{
   ViewData["SearchID"] = id;

   return View();
}

Then in your master page, you can access it in the ViewData

using (Html.BeginForm("Search", "Bing", { id = ViewData["SearchID"] })

For a strongly-typed View, I have a BaseModel class that has properties that the master page needs and all my other models inherit the base class. Something like this...

public class BaseModel
{
   prop string SearchID {get;set;}
}

public class HomeIndexModel : BaseModel
{

}

public ActionResults Index(string id)
{
   HomeIndexModel model = new HomeIndexModel();
   model.SearchID = id;

   return View(model);
}

Your master page would look like this:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<BaseModel>" %>

<% using(Html.BeginForm<BingController>(action => action.Search(Model.SearchID))) { %>
Pete Nelson
Thanks, it works like a charm. Is this valble only for MasterPage or for normal pages too ?
Thomas Jaskula
It will work for every page as well as partial views.
Pete Nelson
yes in fact i wanted to know if need to do this also with a page or partial view. It seems that asp bind the ID automaticaly to the action parameter when it's used in a page.
Thomas Jaskula