我需要知道如何在asp.net mvc 3中的两个控制器之间传递数据 我有两个控制器
public class controller1:Controller
{
}
public class controller2:Controller
{
}
如何将数据从controller1传递到controller2?
答案 0 :(得分:2)
一种方法是使用TempData
传递:
public class controller1Controller:Controller
{
public ActionResult Index()
{
TempData["SomeKey"] = "Some Value";
return RedirectToAction("Index","controller2");
}
}
public class controller2Controller:Controller
{
public ActionResult Index()
{
string value = TempData["SomeKey"] as String;
return View();
}
}
要记住的一件事是TempData
是单一读取,这意味着一旦从TempData
读取一个值,它将自动被删除,如果读取后需要值,则要保留它,你必须致电TempData.Keep()
,你可以通过调用更具体地保持特定的键值:
string value = TempData["SomeKey"] as String;
TempData.Keep("SomeKey");
另一种方法是使用 RouteValue Dictionary :
public class controller1Controller:Controller
{
public ActionResult Index()
{
return RedirectToAction("Index","controller2",new { SomeKey = "SomeValue"});
}
}
public class controller2Controller:Controller
{
public ActionResult Index(string SomeKey)
{
return View();
}
}
我在示例中使用String,您可以使用自定义类型,例如要传递的模型或视图模型对象。
我建议您阅读此MSDN article以获取更多详细信息并了解在mvc应用程序中传递数据。
您还应该阅读What is ViewData, ViewBag and TempData? – MVC options for passing data between current and subsequent request和When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications
答案 1 :(得分:0)
您可以在此处使用 RouteValue Dictionary : -
public class controller1Controller:Controller
{
public ActionResult Index()
{
return RedirectToAction("Index","controller2",new { UserName= "Username"}); <----Just pass username value here
}
}
public class controller2Controller:Controller
{
public ActionResult Index(string UserName) <-----get username value here
{
return View();
}
}