在我的代码后面使用Eval函数?

时间:2014-02-05 15:50:57

标签: asp.net vb.net

这是我的代码:

Partial Class VideoPlayer
Inherits System.Web.UI.Page
Protected strFileName As String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim con As New OleDbConnection
    Dim dbProvider As String
    Dim dbSource As String
    Dim vidID As Integer = Integer.Parse(Request.QueryString("ID"))

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = |DataDirectory|/webvideos.mdb"

    con.ConnectionString = dbProvider & dbSource

    con.Open()
    Dim strSQL As String = "SELECT * FROM Videos WHERE ID=" & vidID
    strFileName = "videos/TrainingVideos/" & Eval("Filename")

    con.Close()
End Sub

End Class

因此,当我运行代码时,它告诉我它无法在我的字符串上运行Eval。我错过了什么?

2 个答案:

答案 0 :(得分:1)

Eval将在您的.aspx代码中使用DataBoundControl。

在代码隐藏中,您正在设置connectionstring,sql查询和其他变量,但实际上并没有执行查询。

所以你的代码应该如下所示:

    Dim con As New OleDbConnection
    Dim dbProvider As String
    Dim dbSource As String
    Dim vidID As Integer = Integer.Parse(Request.QueryString("ID"))

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = |DataDirectory|/webvideos.mdb"

    con.ConnectionString = dbProvider & dbSource

    con.Open()
    Dim strSQL As String = "SELECT * FROM Videos WHERE ID=" & vidID

    //Create an OleDbCommand object.
    //Pass in the SQL query and the OleDbConnection object
    Dim cmd As OleDbCommand = New OleDbCommand(strSQL, con)

    //Execute the command 
    Dim reader As OleDbDataReader = cmd.ExecuteReader 

    //Read the first record from the reader
    reader.Read()
    strFileName = "videos\TrainingVideos\" & reader(1)
    con.Close()

答案 1 :(得分:0)

首先,最重要的是,你在这里开放sql-injection:

"SELECT * FROM Videos WHERE ID=" & vidID

改为使用sql-parameters。

您只能在数据绑定上下文中使用Eval。因此,您需要先致电Me.DataBind

Me.DataBind()
Dim fileName = Me.Eval("Filename").ToString()
strFileName = System.IO.Path.Combine("videos/TrainingVideos", fileName)

然而,我不知道你在这里想要实现的目标。为什么你需要它?

  

全局变量,忘记将其添加到那里。

然后直接访问它。