In this article I will explain with an example, how to add images to
TinyMCE Rich TextBox Editor using ASP.Net FileUpload control in ASP.Net using C# and VB.Net.
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing text.
The TextBox has been assigned with TextMode property set to MultiLine.
FileUpload – For selecting image file.
The Buttons have been assigned with OnClick event handler.
Label – For displaying content of TinyMCE Rich Text Box.
Thee Label has been assigned with Visible property set to false.
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" /><br />
<br />
<asp:TextBox ID="RichTextBox" runat="server" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
<hr />
<asp:Label ID="lblDisplay" runat="server" Text="" Visible="false"></asp:Label>
Applying the TinyMCE Plugin to the TextBox
TinyMCE plugin implementation
Inside the HTML, the following
TinyMCE JS file is inherited.
1. tinymce.min.js
Inside the
Init event handler of the
TinyMCE plugin, the plugin is applied to the TextArea element i.e.
Multiline TextBox
Note: The ASP.Net Multiline TextBox is rendered as TextArea element in HTML, hence the
TinyMCE plugin has been applied to TextArea element.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.0.20/tinymce.min.js"></script>
<script> type="text/javascript">
tinymce.init({ selector: 'textarea', width: 300 });
</script>
Uploading Image to TinyMCE Rich Text Editor
When Upload button is clicked, the FileUpload control is checked for file if it has file then, it is saved in the Images folder.
C#
protected void Upload(object sender, EventArgs e)
{
if (fuUpload.HasFile)
{
string fileName = Path.GetFileName(fuUpload.PostedFile.FileName);
string filePath = "Images/" + fileName;
fuUpload.SaveAs(Server.MapPath(filePath));
RichTextBox.Text += string.Format("<img src='{0}' alt='{1}' style='height:150px;width:150px' />", filePath, fileName);
}
}
VB.Net
Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
If fuUpload.HasFile Then
Dim fileName As String = Path.GetFileName(fuUpload.PostedFile.FileName)
Dim filePath As String = "Images/" & fileName
fuUpload.SaveAs(Server.MapPath(filePath))
RichTextBox.Text += String.Format("<img src='{0}' alt='{1}' style='height:150px;width:150px' />", filePath, fileName)
End If
End Sub
Saving TinyMCE Rich Text Editor content
When
Save button is clicked, the
Visible property of the Label control is set to true and contents of the
TinyMCE Rich TextBox Editor is set to it.
C#
protected void Save(object sender, EventArgs e)
{
lblDisplay.Visible = true;
lblDisplay.Text = RichTextBox.Text;
}
VB.Net
Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)
lblDisplay.Visible = True
lblDisplay.Text = RichTextBox.Text
End Sub
Screenshot
Download