asp.net-mvc 如何将值从一个动作传递给具有相同控制器的另一个动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23677456/
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
How to pass value from one action to another action having same controller
提问by Abhay Singh
Hi I am developing an application in MVC3. and i am stuck at one place. Everytime when control goes to IIndex1action its argument value has become 0. But it should be same as value in IIndexaction argument. I have used session, ViewBag, ViewData but my problem is remains. Please suggest me.
嗨,我正在 MVC3 中开发一个应用程序。我被困在一个地方。每次控制执行IIndex1动作时,其参数值都变为 0。但它应该与IIndex动作参数中的值相同。我使用过 session、ViewBag、ViewData,但我的问题仍然存在。请建议我。
public ActionResult GetMDN(string msisdn)
{
number = msisdn.Substring(0, msisdn.IndexOf('$'));
if (number.ToLower() != "unknown" && number.Length == 12)
{
number = number.Remove(0, 2);
}
Session["msdresponse"] = number;
Session["moptr"] = msisdn.Substring(msisdn.LastIndexOf('$') + 1);
number = msisdn;
int sngid=int.Parse(ViewData["isongid"].ToString());
return RedirectToAction("IIndex1", new { iid = sngid });
}
public ActionResult IIndex(int id)
{
ViewBag.isongid = id;
ViewData["isongid"] = id;
Response.Redirect("http:XXXXXXXXXXXXXXXX");
return RedirectToAction("GetMDN");
}
public ActionResult IIndex1(int iid)
{
}
回答by Badhon Ashfaq
You can use TempData.You can pass every types of data between to action, whether they are in same controller or not. Your code should be something like it:
您可以使用 TempData。您可以在操作之间传递各种类型的数据,无论它们是否在同一个控制器中。你的代码应该是这样的:
public ActionResult GetMDN(string msisdn)
{
int sngid=10;
TempData["ID"] = sngid;
return RedirectToAction("IIndex");
}
public ActionResult IIndex()
{
int id = Convert.ToInt32(TempData["ID"]);// id will be 10;
}
回答by st4hoo
Use TempData instead of ViewData/ViewBag to store data that should persist after redirect. ViewData/ViewBag allow to pass value from controller to view.
使用 TempData 而不是 ViewData/ViewBag 来存储重定向后应该保留的数据。ViewData/ViewBag 允许将值从控制器传递到视图。
Something to read on this subject:
关于这个主题的一些内容:
http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem
http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem
http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).aspx
http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).aspx

