【问题标题】:Not able to access class level private variables from different methods/functions of the same class无法从同一类的不同方法/函数访问类级私有变量
【发布时间】:2012-01-04 20:11:25
【问题描述】:

在下文中,我试图在名为 _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

【问题讨论】:

    标签: asp.net asp.net-mvc variables private


    【解决方案1】:

    这根本不可能。

    每个 HTTP 请求都有一个单独的控制器实例;他们不分享任何东西。

    您应该酌情使用 cookie、会话、应用程序状态或缓存。

    在您的情况下,您可能应该将该变量包含在来自&lt;form&gt; 的其他操作的 POST 中。

    【讨论】:

    • 每个请求都会获得一个新的控制器实例,这对我来说很新鲜。但是下面的情况呢: View # 1 将一些数据发送回控制器,基于该数据 View # 2 显示给用户。 View # 2 发回数据,最后 View # 3 合并从 View # 1 、 2 和 3 获得的所有内容并显示给用户。它是如何完成的?我在这里有意义吗?
    • @user1001493:您需要在每次回发时传递所有数据,或者使用会话。
    【解决方案2】:

    如果你不想添加正式的 post 参数,你可以使用

    TempData.Add("P", P);
    

    就在返回语句之前,您可以在 ListOfVeicles 中通过

    string p = TempData["P"];
    

    临时数据仅在请求范围内有效

    编辑:对不起 C# 语法,自从 VB 6 的好时光以来,我没有使用 VB

    【讨论】:

    • 感谢您的回复 这确实有效并解决了我的问题。关于它的使用有什么特别的问题吗?像性能,安全性等?有没有其他方法可以实现相同的目标(任何行业特定的最佳实践)?
    • 不,正是出于这个原因添加了 TempData,我只是添加至少使用常量作为 TempData 名称(我讨厌代码中的魔术字符串)。 TempData 是短暂的,因此它不会增加安全问题。
    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 2012-09-24
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多