предполагая date
строковая переменная, Вы хотели бы сделать следующее:
log = trim(request.form("log1")) & "<br>" & [date] & ": " & trim(request.form("txb1"))
также, если date
является переменной DateTime, вы бы хотели использовать date.ToShortDateString()
и вместо <br/>
я бы рекомендовал использовать Environment.NewLine
и даже лучше, вы должны использовать StringBuilder:
Dim SB As New StringBuilder()
SB.AppendLine(trim(request.form("log1")))
SB.AppendLine([date] & ": " & trim(request.form("txb1")))
log = SB.ToString()
UPDATE:
если вы хотите сохранить весь журнал в одной записи, а не в отдельной таблице, то лучше сохранить его как список журналов в столбце varbinary(MAX)
.
вот полный пример того, как это сделать:
1. Мы начнем с созданием <div>
элемента, который будет содержать наши красивые журналы и будет обрабатываться сервером, и текстовое поле для новых журналов :
<asp:TextBox ID="txb1" runat="server"></asp:TextBox>
<div id="Text_Div1" runat="server"></div>
2. Теперь в коде позади, мы создаем класс для удержания 1 одну строку лога:
'create a log class and state that it serializable
<Serializable> _
Public Class MyLogRecord
Public Sub New(_msg As String)
[Date] = DateTime.Now
Message = _msg
End Sub
Public Property [Date]() As DateTime
Get
Return m_Date
End Get
Set
m_Date = Value
End Set
End Property
Private m_Date As DateTime
Public Property Message() As [String]
Get
Return m_Message
End Get
Set
m_Message = Value
End Set
End Property
Private m_Message As [String]
Public Function ToText() As String
Return [Date].ToShortDateString() & ": " & Convert.ToString(Message)
End Function
End Class
3.где бы вы обновляете журналы, будь его button_click или textbox_keydown, вы делаете следующее:
' create a list of logs
Dim MyLogs As List(Of MyLogRecord)
'check if we stored the logs already in the session,
'if yes, retrieve it from the session var,
'if not then create a new one.
If Session("MyLogs") IsNot Nothing Then
MyLogs = DirectCast(Session("MyLogs"), List(Of MyLogRecord))
Else
MyLogs = New List(Of MyLogRecord)()
End If
' create a new log record from the new textbox value
Dim _tempLog As New MyLogRecord(txb1.Text)
'add the new log to the list
MyLogs.Add(_tempLog)
'save it back in a session var:
Session("MyLogs") = MyLogs
4. В той части, где вы сохраните журналы в БД MySQL, вы делаете это таким образом: первый преобразовать список в массив байтов и сохранить его в varbinary(MAX)
колонке
'create a new binary formatter, include System.Runtime.Serialization.Formatters.Binary;
Dim formatter As New BinaryFormatter()
'create a byte array to store our logs list
Dim _logsBinary As Byte()
'create a memory stream to write the logs list into
Using _logStream As New MemoryStream()
'use the formatter to serialize the list in to an array of bytes
'directly into the memory stream
formatter.Serialize(_logStream, MyLogs)
'dump the memory stream into the byte array
_logsBinary = _logStream.ToArray()
End Using
' ... save the _logsBinary into mysql as a 'varbinary(max)' ...
5. в том месте, где вы получить журналы из БД MySQL, вы десериализации массив байтов обратно в список журналов:
Dim MyLogs As New List(Of MyLogRecord)()
Dim formatter As New BinaryFormatter()
Using _logStream As New MemoryStream()
_logStream.Write(_logsBinary, 0, _logsBinary.Length)
_logStream.Position = 0
' de-serialize the byte array back into a logs list
MyLogs = DirectCast(formatter.Deserialize(_logStream), List(Of MyLogRecord))
End Using
6. в том месте, где вы пишете журналы на вашей странице, вы делаете это так:
Dim SB As New StringBuilder()
' create a temp date to compare against all the records,
' and initialize it with the first value or else you will have
' a orizontal line before the first row
Dim _prevDate As DateTime = MyLogs.First().[Date]
For Each _logRec As MyLogRecord In MyLogs
'take the date of the currently iterrated item and
'compare against the temp date, note that comparing months is not enough,
'month might be same/earlier but year can be higher
Dim _currentDate As DateTime = _logRec.[Date]
If _currentDate.Month > _prevDate.Month OrElse _currentDate.Year > _prevDate.Year Then
'append horizontal line
SB.AppendLine("<hr/>")
'update temp value
_prevDate = _currentDate
End If
'finally append the log: ToText() is the class custom
'function that we created above
SB.AppendLine(_logRec.ToText())
Next
'dump the logs into the server managed div:
Text_Div1.InnerHtml = SB.ToString()
Вы хотите сделать это на стороне клиента или на стороне сервера и нажать на дб ? –
@SivaGopal 'Request.Form' должен отдать свою серверную операцию ... – Banana
@Banana Что мне интересно, так как он использует Asp.net, он мог бы использовать те сами теги textbox/textarea (например: txb1. Текст). Почему он идет по этому жесткому маршруту Request.Form? У него были какие-либо элементы html на стороне клиента? –