无法从同一类的不同方法/函数访问类级私有变量
下面我尝试在类级别定义一个名为 _p 的私有变量。索引的 HTTP.POST 将带来用户提供的值,我将使用该值设置此私有变量。在名为 ListOfVehicles 的第二个方法中,我将访问此变量。
现在理论上一切都很好,但是当我尝试访问这个私有变量时我什么也没有得到,什么也没有发现。
Public Class QuotationController
Inherits System.Web.Mvc.Controller
'Private Variables
Dim _p As String
'Get Basic pickup and dropoff details
Function Index() As ActionResult
Return View()
End Function
'Function to get basic details out of the view
'and to redirect to ListOfVehicles
<HttpPost()>
Function Index(ByVal P As String, ByVal D As String) As ActionResult
_p = P
Return RedirectToAction("ListOfVehicles")
End Function
'Show list of vehicels
Function ListofVehicles() As ActionResult
ViewData("UserChoice") = "Pickup: " & _p
vehicleList = QB.GetQuotation(_p, _d)
Return View(vehicleList)
End Function
End Class
In the following I am trying to define a Private variable on Class level called _p. The HTTP.POST for Index will bring a User provided value which I'll set this private variable with. In the second Method called ListOfVehicles, I'll be accessing this variable.
Now everything is alright theoretically, however when I try to access this private variable I don't get anything, this is found Nothing.
Public Class QuotationController
Inherits System.Web.Mvc.Controller
'Private Variables
Dim _p As String
'Get Basic pickup and dropoff details
Function Index() As ActionResult
Return View()
End Function
'Function to get basic details out of the view
'and to redirect to ListOfVehicles
<HttpPost()>
Function Index(ByVal P As String, ByVal D As String) As ActionResult
_p = P
Return RedirectToAction("ListOfVehicles")
End Function
'Show list of vehicels
Function ListofVehicles() As ActionResult
ViewData("UserChoice") = "Pickup: " & _p
vehicleList = QB.GetQuotation(_p, _d)
Return View(vehicleList)
End Function
End Class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这根本上是不可能的。
每个 HTTP 请求都会获得一个单独的控制器实例;他们不分享任何东西。
您应该根据需要使用 cookie、会话、应用程序状态或缓存。
在您的情况下,您可能应该将该变量包含在
That is fundamentally impossible.
Each HTTP request gets a separate controller instance; they don't share anything.
You should use cookies, session, application state, or cache, as appropriate.
In your case, you should probably include that variable in a POST to the other action from a
<form>
.如果您不想添加正式的 post 参数,您可以
在 return 语句之前使用,在您的 ListOfVeicles 中,您可以通过
临时数据访问仅在请求范围内有效
编辑:抱歉 C# 语法,我不使用 VB从 VB 6 的美好时光开始
If you don't want to add a formal post parameter you can use
just before the return statement, in your ListOfVeicles you can accesso via
Temp data is valid just within the request scope
EDIT: sorry for C# syntax, I'm not using VB since the good old days ov VB 6