Tomasz Jaskuλa
Tomasz Jaskuλa

Reputation: 16013

ASP.NET MVC and passing ID to strongly typed BeginForm

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

Upvotes: 2

Views: 1206

Answers (1)

Pete Nelson
Pete Nelson

Reputation: 1338

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))) { %>

Upvotes: 3

Related Questions