在 Html.BeginForm MVC 中传递多个参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17013669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass multiple parameters in Html.BeginForm MVC
提问by Andy Johnston
I have something like this:
我有这样的事情:
public ActionResult Create(int clubid)
{
var club = db.Clubs.Single(c=>c.Id == clubid);
ViewBag.Club = club;
Competition comp = db.Competitions.Create();
return View(comp)
}
and in my .cshtml:
在我的 .cshtml 中:
@Model Models.Competition
...
@Using(Html.BeginForm())
{
...
<input type="submit" value="Save" />
}
This works fine with the following Post Action:
这适用于以下发布操作:
[HttpPost]
public ActionResult Create(Competition comp)
{
if (ModelState.IsValid){...}
return RedirectToAction(...);
}
However, I want to pass an additional parameter from the @ViewBag.Club
object:
但是,我想从@ViewBag.Club
对象传递一个附加参数:
[HttpPoSt]
public ActionResult Create(int clubid, Competition comp){...}
How do I code this in the BeginForm
?
我如何在BeginForm
?
回答by Johan
There are two options here.
这里有两个选项。
- a hidden field within the form, or
- Add it to the route values parameter in the begin form method.
- 表单中的隐藏字段,或
- 将其添加到开始表单方法中的路由值参数中。
Edit
编辑
@Html.Hidden("clubid", ViewBag.Club.id)
or
或者
@using(Html.BeginForm("action", "controller",
new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)
回答by JQII
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
我喜欢的另一种选择是使用一个控制器重定向到另一个控制器,一旦我开始看到不符合 DRY 的代码,就可以将其推广。
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
我发现这允许我在一个位置应用我的逻辑并重新使用它,而不必在视图中添加 JavaScript 来处理这个问题。而且,正如我提到的,当我看到这被滥用时,我可以重构以重新使用。