在一个控制器中保留两个操作结果之间的值
我正在控制器的一种操作方法中生成值。如何在同一控制器的另一个操作结果中使用相同的变量值?
例如:
控制器 A - 操作结果 1 :
public ActionResult CalculationsONE()
{
dynamic CalcModel = new ExpandoObject();
int var1 = //Value calculated here
int var2 = //Calculation
CalcModel.Var1= var1;
CalcModel.Var2= var2;
return View(CalcModel);
}
控制器 A - 操作结果 2:
public ActionResult CalculationsTWO()
{
// I want to use var1 and var2 from the CalculationsONE in
this action result
}
I am generating values in one action method of a controller. How can I use the same variables values in another action result from the same controller?
For example:
Controller A - Action result 1 :
public ActionResult CalculationsONE()
{
dynamic CalcModel = new ExpandoObject();
int var1 = //Value calculated here
int var2 = //Calculation
CalcModel.Var1= var1;
CalcModel.Var2= var2;
return View(CalcModel);
}
Controller A - Action result 2:
public ActionResult CalculationsTWO()
{
// I want to use var1 and var2 from the CalculationsONE in
this action result
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需将它们作为查询字符串参数传递即可:
为了从
CalculationsONE
操作中呈现的视图中调用CalculationsTWO
操作,您可以生成如下链接:哦,我建议您使用强类型视图模型而不是传递给视图的动态对象。
ViewBag
是动态的,但老实说,使用视图模型。你会更幸福:-)Simply pass them as query string parameters:
and in order to invoke the
CalculationsTWO
action from within the view rendered inCalculationsONE
action you could generate a link like this:Oh, and I would recommend you using strongly typed view models instead of dynamic objects passed to the view.
ViewBag
is dynamic but honestly, use view models. You will be happier :-)如果它们是两个单独的操作,那么达林·迪米特洛夫的上述答案应该这样做,否则如果您希望在一个资源调用中得到两个结果,请在控制器中创建两个私有方法来执行 calc1 和 calc2 并将结果返回到视图...
您可以使用像您当前这样的类变量要跟踪值。
If they are two separate actions the above answer from Darin Dimitrov should do it otherwise if you want both results in one resource call create two private methods in your controller that do calc1 and calc2 and return the results to the view...
you can use class vars like you currently are to keep track of the values.
作为替代方案,我会通过将变量保存到会话中的方式来解决此问题。
EG:
或者通过 ViewData["string"] 将它们传递到视图中,并在 Request.FormData["VariableName"] 上的控制器中将其绑定回
另一种方式是
将数据添加到视图的模型中
并在控制器中回发时将模型绑定回变量,
例如:
其中模型定义是:
As alternative I would go about it in way of saving your variables into session.
EG:
or pass them via ViewData["string"] into view and in Controller on Request.FormData["VariableName"] to bind it back
another way is
add the data to model for the view
and on postback in your controller bind the model back into variable
eg:
Where Model definition is: