ASP.NET MVC 并将 ID 传递给强类型 BeginForm

发布于 2024-08-20 06:50:27 字数 298 浏览 8 评论 0原文

我在将 id 从 URL 传递到控制器操作时遇到一些问题

假设我有这个 Url:Bing/Index/4

在我的母版页中,我想生成一个提交到 BingController SearchAction 的表单。我做了这样的事情

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

如何从 url 获取 id(本例中为 4)并将其传递给搜索行动?

感谢您的帮助

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坏尐絯℡ 2024-08-27 06:50:27

要访问母版页中的数据,您的控制器需要将其添加到 ViewData 中,以便母版页可以访问它。

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

   return View();
}

然后在母版页中,您可以在 ViewData 中访问它。

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

对于强类型视图,我有一个 BaseModel 类,它具有母版页所需的属性,并且我的所有其他模型都继承基类。像这样的东西......

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);
}

你的母版页看起来像这样:

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

<% using(Html.BeginForm<BingController>(action => action.Search(Model.SearchID))) { %>

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))) { %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文