[英]How to pass a value from a controller method to an another?
I'm beginner in MVC3, and I want to get a value from an another controller's method. 我是MVC3的初学者,我想从另一个控制器的方法中获取一个值。 Here the two methods:
这里有两种方法:
[HttpPost]
public ActionResult Create(TennisClub tennisclub)
{
if (ModelState.IsValid)
{
db.TennisClubs.Add(tennisclub);
db.SaveChanges();
return RedirectToAction("AssignManager");
}
return View(tennisclub);
}
[HttpPost]
public ActionResult AssignManager(Manager manager)
{
}
So, when I'm creating a new tennis club, Immediately I would like to assign a manager to it... For that I need the primary key "ID". 因此,当我创建一个新的网球俱乐部时,我想立即为其分配一个经理...为此,我需要主键“ ID”。
So my question is: How to get this ID in my "AssignManager" method ? 所以我的问题是:如何在我的“ AssignManager”方法中获取此ID? Thanks in advance
提前致谢
You cannot redirect to an action decorated with the [HttpPost]
attribute. 您不能重定向到使用
[HttpPost]
属性修饰的动作。 That's not how a redirect works. 重定向不是这样工作的。 A redirect means that you are sending a 301 HTTP status code to the client with the new Location header and the client issues a GET request to this new location.
重定向意味着您正在使用新的Location标头向客户端发送301 HTTP状态代码,并且客户端向该新位置发出GET请求。
So once you remove the [HttpPost]
attribute from your AssignManager action you could pass the id as parameter: 因此,一旦从AssignManager操作中删除
[HttpPost]
属性,就可以将id作为参数传递:
return RedirectToAction("AssignManager", new { id = "123" });
and then: 接着:
[HttpPost]
public ActionResult AssignManager(int id)
{
}
return RedirectToAction("AssignManager", new { id = tennisclub.Id });
Also you need to remove the [HttpPost]
attribute from your action 另外,您还需要从操作中删除
[HttpPost]
属性
public ActionResult AssignManager(int id) {
//...
}
Basically, you need to have a GET
AssignManager method, too, which would have a parameter telling it to which TennisClub
the manager should be assigned: 基本上,您还需要有一个
GET
AssignManager方法,该方法将带有一个参数,告诉该管理器应该分配给哪个TennisClub
:
[HttpGet]
public ActionResult AssignManager(int tennisClubId)
{
// here, you will want to return AssignManager view
}
And when redirecting to AssignManager
from Create
, you can specify the id of TennisClub
: 当从
Create
重定向到AssignManager
时,您可以指定TennisClub
的ID:
return RedirectToAction("AssignManager", new { tennisClubId = tennisclub.Id });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.