我正在使用ASP.NET MVC 3来构建Web应用程序.
我想要做的是在两个控制器之间传递值,虽然有很多方法可以做到这一点我特别感兴趣的是使用TempData它.
public ActionResult Action1()
{
string someMessage;
Test obj = SomeOperation();
if(obj.Valid)
{
someMessage = obj.UserName;
}
else
{
someMessage = obj.ModeratorName;
}
TempData["message"] = someMessage;
return RedirectToAction("Index");
}
public ActionResult Index()
{
ViewBag.Message = TempData["message"]
return View();
}
Run Code Online (Sandbox Code Playgroud)
那么TempData这里的使用是否正确?我的意思是在最好的编程实践中使用这种正确的方法TempData吗?
在什么时候应该TempData使用案例?
注意:我已经通过以下链接
谢谢
我在ASP.Net MVC中创建一个ActionResult来提供图像.启用会话状态后,IIS将一次只处理来自同一用户的一个请求.(这不仅适用于MVC.)
因此,在具有多个图像回调此Action的页面上,一次只能处理一个图像请求.这是同步的.
我希望这个图像Action是异步的 - 我希望每次执行多个图像请求而不需要前一个完成.(如果图像只是静态文件,IIS会以这种方式为它们提供服务.)
所以,我想禁用Session仅用于对该Action的调用,或者指定某些请求没有Session状态.任何人都知道如何在MVC中完成这项工作?谢谢!
我有一个ASP.NET MVC在线商店类应用程序,有两个视图:
用户成功提交表单后,应将其重定向回项目页面,并在顶部显示一次性消息:"您的评论已成功提交".
控制器代码(简化)如下所示:
[HttpGet]
public ActionResult ViewItem([Bind] long id)
{
var item = _context.Items.First(x => x.Id == id);
return View(item);
}
[HttpGet]
public ActionResult AddReview()
{
return View();
}
[HttpPost]
public ActionResult AddReview([Bind] long id, [Bind] string text)
{
_context.Reviews.Add(new Review { Id = id, Text = text });
_context.SaveChanges();
return RedirectToAction("ViewItem");
}
Run Code Online (Sandbox Code Playgroud)
有几个要求要满足:
我想将消息存储在用户会话中并在显示后将其丢弃,但是可能有更好的解决方案吗?
我有一个MVC控制器,我希望将相同的(静态)信息传递给同一控制器中的任何ActionResult ,只能由同一用户在索引页面中的新选项进行更改.我已经读过使用静态变量被认为是不好的做法.我的网站在Intranet环境中使用Windows身份验证,任何时候最多可以有10个人查看任何一个页面.如果我理解我正确阅读的内容,则存在一个危险,即静态变量可以被页面用户以外的其他人覆盖,只需同时查看同一页面即可.
作为替代方案,我读到了"TempData"和"Session Variables",但到目前为止,我还没有读到任何指示这些方法是否能确保仅在查看该页面实例的人员的索引页面中设置变量的任何内容.我在下面粘贴了代码示例,显示了我的意思.我让他们工作,我的问题是哪种方法确保只有查看该页面实例的人设置并读取值?
此代码示例显示了控制器级静态变量的使用:
public class HomeController : Controller
{
public static string _currentChoice;
public ActionResult Index(string CurrentChoice)
{
_currentChoice = string.IsNullOrEmpty(CurrentChoice)?"nothing":CurrentChoice;
ViewBag.Message = "Your choice is " + _currentChoice;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your choice is still "+_currentChoice;
return View();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码示例使用TempData和Session:
public class HomeController : Controller
{
public ActionResult Index(string CurrentChoice)
{
var _currentChoice = CurrentChoice;
_currentChoice = string.IsNullOrEmpty(CurrentChoice)?"nothing":CurrentChoice;
TempData["CurrentChoice"] = _currentChoice;
Session["SessionChoice"] = _currentChoice; …Run Code Online (Sandbox Code Playgroud)