I am getting an error when I try to post data from an asp textbox to the database. The reason for this is that the text is html due to using an html text editor.
However when I try to encode the html I get the following error: BC30451: 'Bind' is not declared. It may be inaccessible due to its protection level.
Below is the asp code I have for the textbox that's causing the error.
<asp:TextBox ID="TxtBx" runat="server" Text='<%# Server.HtmlEncode(Bind("Details").ToString())%>'/>
I'm sure it's something small but can't resolve it. I have also tried the below with the same outcome:
Text='<%# System.Web.HttpUtility.HtmlEncode(Bind("Details"))%>'
I have also attempted to create my own function in the backend to resolve this with the following asp and vb:
Text='<%# encodeIT(Eval("Details"))%>'
Public Function encodeIT(Details As String) As String
Return HttpUtility.HtmlEncode(Details)
End Function
Any help would be greatly appreciated.
Update 1
I have attempted a client solution but still doesn't appear to be working, not sure if I've missed something, been testing in a basic web project to avoid any compatibility issues that could crop up. I have removed the databind for the purpose of this test as ASP throws the same error regardless.
ASP
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script src="../Scripts/tinymce/tinymce.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
tinymce.init({
menubar: false,
width: 800,
height: 250,
selector: "textarea"
});
var decodeStuff = (function () {
// preventing any overhead from creating more than one instance of the function
var element = document.createElement('div');
function decodeHtml(str) {
if (str && typeof str === 'string') {
// strip script and html tags
str = str.replace(/<script>[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeStuff;
});
var text = decodeStuff('TxtBx');
});
</script>
<asp:Panel runat="server" ID="panel1">
<table>
<tr>
<td>
<asp:TextBox ID="TxtBx" runat="server" Width="100%" TextMode="MultiLine" Rows="20"></asp:TextBox>
</td>
</tr>
Code behind (VB) where I'm trying to call the function on post back.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If DDL.Text <> "Select" Then
TxtBx.Text = DDL.Text``
End If
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "TxtBx", "decodeHtml();", True)
End Sub
If this is only for internal use go into the web config file and within system.web you'll find httpRunTime and Pages add attributes requestValidationMode="2.0" and validateRequest="false" respectively.
Code:
<httpRuntime requestValidationMode="2.0"/>
<pages validateRequest="false"/>
Related
<script type="text/javascript">
function GetValue3(id) {
text1 = documnet.getElementById(input parameter from cs file);
alert("this is from cs file");
//database transactions here <-------method1
}
$(function () {
button1 = document.getElementById(input parameter from aspx file);
$("[id*=Button1]").on("click", function () {
alert("this is from aspx file");
//database transactions here <-------method2
})
})
</script>
My question is that there are two procedures for database transactions, first from taking parameters from aspx.cs code befind file and second from aspx file.
In my code i want to do database transactions using second approach (by using parameters from aspx.cs code behind) because it is required in my coding.
please guide me how can i build this approach.
not sure what you are trying to achieve but you need to differentiate between client events and server events
to get element in JS you can get its ID from 'ClientID'
ASPX file:
<asp:TextBox ID="txtTest" OnTextChanged="txtTest_TextChanged" runat="server" AutoPostBack="true" ></asp:TextBox>
<asp:Button ID="btn1" OnClick="btn1_Click" runat="server" Text="Click" />
<script type="text/javascript">
function textFromTextBox() {
var text1 = documnet.getElementById('<%= this.txtTest.ClientID %>');
}
</script>
aspx cs file
protected void btn1_Click(object sender, EventArgs e)
{
var text = txtTest.Text;
}
protected void txtTest_TextChanged(object sender, EventArgs e)
{
var updatedText = txtTest.Text;
}
EDIT:
you cannot attach code behind method to ordinary html element. You can only attach javascript events to these elements or inputs. If its the case then its irrelevant if you are using asp.net web forms, python, ruby on backend server.
<input type="button" id="sbutton" value="Save" />
<script type="text/javascript">
(function (){
documnet.getElementById('sbutton').addEventListener("click", function(){ //do your crud operation });;
})
()
</script>
I have two separate pages. One with a HTML page involving JavaScript (bunch of functions etc.) and an .aspx page.
I have some array in html page and I want to send them(using JavaScript) to .aspx to store them into a database.
I have tried hidden field, creating a form etc. All I get is null. How can I pass my arrays to aspx to store them in database later? I can't use jQuery.
function openPopup() {
window.open("Default.aspx", "scrollbars=yes, width=900,height=500,left=430,top=100");
return false;
}
function control() {
var a = JSON.stringify(x);// x and y are my arrays
var b = JSON.stringify(y);
var btnId = '<%= HiddenField1.ClientID%>';
var btnId2 = '<%= HiddenField2.ClientID%>';
document.getElementById(btnId).value = a;
document.getElementById(btnId2).value = b;
}
IN HTML
<button onclick="openPopup()">POP</button> //opens the aspx page
IN ASPX
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Database" />
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:HiddenField ID="HiddenField2" runat="server" />
</form>
IN ASPX.CS
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(HiddenField1);
}
You will need to send the data to the server using AJAX (preferably) or using a traditional form submission (page will be reloaded after submission).
The server cannot access the HTML elements once the page has been rendered in the browser.
I'm a fresh of ASP.NET, I meet the problem in my work, please help.
I want to dynamically add the options into a dropdownlist in ASP page.
So I write a javascript function:
<body>
<form id="form1" runat="server" style="height:100%">
</form>
<script type="text/javascript">
function addOptionToSelect(optKey, optValue) {
var select = document.getElementById('<%=mySelect.ClientID%>');
var opt = new Option(thisLabel, thisValue);
select.add(opt);
}
}
</script>
</body>
For some reasons, I have to add the dropdownlist web control in code-behind of the ASP:
protected void Page_Load(object sender, EventArgs e)
{
Table t = new Table();
form1.Controls.Add(t);
TableRow r = new TableRow();
formatTable.Rows.Add(r);
TableCell c = new TableCell();
formatRow.Cells.Add(c);
DropDownList select = new DropDownList();
select.ID = "mySelect";
select.Text = "mySelect:";
c.Controls.Add(select);
}
I will get the error:
Compiler Error Message: CS0103: The name 'mySelect' does not exist in the current context.
However, if I add the dropdownlist in ASP page directly, there is no error.
<form id="form1" runat="server" style="height:100%">
<div>
<asp:DropDownList ID="a_content_type" runat="server">
</asp:DropDownList>
</div>
</form>
How should I solve the error? And What's the difference of "add asp web control in ASP page" and "add asp web control in code-behind"?
I think I find another way to solve the problem. First, I add a new function in the ASP Header:
function setClientID(id) { this.clientID = id; }
Then, add the below code to code-behind after creating dropdownlist:
Page.ClientScript.RegisterStartupScript(this.GetType(), "setClientID", "setClientID('" + mySelect.ClientID + "');", true);
Finally, user "this.ClientID" to replace the "<%=mySelect.ClientID%>".
It works.
here is example:
abcd.aspx
<asp:TextBox ID="txtFName" runat="server" ></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login"
onclick="btnLogin_Click" OnClientClick = "loginAlert()" />
javascriptfile.js
function loginAlert() {
var name = document.getElementById('<% txtFName.ClientID %>').value;
alert(name);
}
link to javascript file on .aspx page
<script src="../../JSfiles/javascriptfile.js" type="text/javascript"></script>
here name is not appear on popup box.
You can't use code nuggets (<% and %>) inside normal files (like your javascriptfile.js) since they're not interpreted by ASP.NET in any way. What you could do is to pass the Id of the text-box to a function:
function loginAlert(ctrl) {
var name = document.getElementById(ctrl).value;
alert(name);
}
Then the markup will look like the following:
<asp:Button ID="btnLogin" runat="server" Text="Login"
OnClick="btnLogin_Click" OnClientClick="loginAlert('<%=txtFName.ClientID%>')" />
UPDATE
I didn't pay attention to the fact that construct like <%=...%> don't work in server-side control declarations (because they're basically converted to Response.Write statements when the page is compiled). There're at least two ways to solve this problem:
You can make the reference to the DOM element for the name text-box globally available. Your markup will look like the following:
<script type="text/javascript">
var loginNameId = '<%=txtFName.ClientID%>';
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login"
OnClick="btnLogin_Click" OnClientClick="loginAlert()" />
And your loginAlert will look like the following:
function loginAlert() {
var name = document.getElementById(loginNameId).value;
alert(name);
}
I personally don't like this solution since you pollute the global namespace with variables and it's not very elegant in general.
Alternatively you can use data attributes together with ASP.NET data binding.
Markup:
<asp:Button ID="btnLogin" data-name='<%# txtFName.ClientID %>' runat="server" Text="Login"
OnClick="btnLogin_Click" OnClientClick="loginAlert(this)" />
JavaScript:
function loginAlert(ctrl) {
var name = document.getElementById(ctrl.readAttribute('data-name')).value;
alert(name);
}
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
DataBind();
}
The javascript file is not served by the ASP.Net parser. Thus, the <% %> is ignored and output as is.
The simpliest way is to provide the ID as parameter:
<asp:TextBox ID="txtFName" runat="server" ></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login"
onclick="btnLogin_Click" />
code behind :
btnLogin.OnClientClick = string.Format("loginAlert('{0}')", txtFName.ClientID);
and in the js file:
function loginAlert(txtId) {
var name = document.getElementById(txtId).value;
alert(name);
}
Markup <% %> wont work in JS files. If you put it on aspx page inside <script type='text/javascript'>...</script> then it will work.
Update:
If you want to get client id, then you can register it from code behind in a variable, as:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "JsVariables", "var txtboxClientId='" + txtFName.ClientID + "';", true);
and in Js file use:
function loginAlert() {
var name = document.getElementById(txtboxClientId).value;
alert(name);
}
<asp:ScriptManager ID="ScriptManager1" ScriptMode="Release" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
var elem = args.get_postBackElement();
alert("begin " + elem.value);
}
function EndRequestHandler(sender, args) {
alert("end request handler");
}
</script>
This is my simple attempt to retrieve the postback element, triggered from my UpdatePanel. My update panel looks like this:
<asp:UpdatePanel ID="UpdatePanel_Project" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList_Project" runat="server">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList_Customer" />
</Triggers>
</asp:UpdatePanel>
I believe I have did everything correctly...
Any ideas?
You have to set the ClientIDMode property value of the control (the DropDownList_Customer drop down list in this case) to AutoID. Please view my reply here.
What is your postback trigger ? This control seems to be missing DropDownList_Customer
<asp:AsyncPostBackTrigger ControlID="DropDownList_Customer" />
I finally solved this pain, here's my solution.
Basically we just need to override Microsoft's _uniqueIDToClientID function so it doesn't ignore our Static client Ids on postback elements.
You'll just need to add the following code at the bottom of your page.
if (Sys.WebForms.PageRequestManager) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm._uniqueIDToClientID = function (uniqueID) {
var clientID = uniqueID.replace(/\$/g, "_");
if (document.getElementById(clientID)) {
return clientID;
}
var lastDollar = uniqueID.lastIndexOf("$");
if (lastDollar === -1) {
return clientID;
}
if (lastDollar+1 > uniqueID.length) {
return clientID;
}
var staticID = uniqueID.slice(lastDollar + 1);
return document.getElementById(staticID) ? staticID : clientID;
};
}
Now, get_postBackElement() in your BeginRequestHandler will no longer be undefined!
Just make sure our code is executed after Microsoft's MicrosoftAjaxWebForms.js because we are overriding its _uniqueIDToClientID function.
Note: My function always returns the default WebForms ClientID if the element exists on the page. Only if the element cannot be found on
the page, does it check to see if an element with a static ID exists
on the page. If it exists, the staticID is used, otherwise it
defaults back to the default WebForms ClientID.