I am trying to access a asp:panel in an external script to make it not visible,but it does not seem to be working. When the Script is in the .aspx file it works fine though.Any suggestions?
In the .aspx file
<script src="App_Themes/custom.js"></script>
<asp:Button ID="descriptionButton" Text="Description" runat="server" OnClientClick="descButton(); return false;" />
<asp:Panel ID="desciptionPanel" runat="server">
///random stuff
<asp:panel>
in the custom.js file
function descButton() {
var desc = document.getElementById('<%=desciptionPanel.ClientID%>');
desc.style.visibility = "visible";
desc.style.height = "800px";
}
Thanks in advance
Split it to two.
First, in the aspx at the server, leave the ID so that you can reuse it later
<script>
window.panelID = '<%= whatever.ClientID %>';
</script>
Then, in an external script, just use the ID
function externalJSfunction() {
var desc = document.getElementById(window.panelID);
}
Use a parameter to your function
OnClientClick="descButton('<%=desciptionPanel.ClientID%>');
then script will be
function descButton(id) {
var desc = document.getElementById(id);
desc.style.visibility = "visible";
desc.style.height = "800px";
}
Related
I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?
You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.
It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>
I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.
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"/>
Doing some javascript for the first time.
I'm playing around with a sessiontimeout and it was working well while I had the code within the .aspx page.
Next stape was to put the code in a .js page. So here's my current lineup.
Script.aspx.js
var iddleTimeoutWarning = null;
var iddleTimeout = null;
function pageLoad()
{
if (iddleTimeoutWarning != null)
clearTimeout(iddleTimeoutWarning);
if (iddleTimeout != null)
clearTimeout(iddleTimeout);
var millisecTimeOutWarning = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeoutWarning"]) * 60 * 1000 %>;
var millisecTimeOut = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeout"]) * 60 * 1000 %>;
iddleTimeoutWarning = setTimeout("DisplayIddleWarning()", millisecTimeOutWarning);
iddleTimeout = setTimeout("TimeoutPage()", millisecTimeOut);
}
function DisplayIddleWarning()
{
document.getElementById("LblWarning").innerHTML = "Warning Message";
}
function TimeoutPage()
{
__doPostBack('FiresAutoIdle','');
}
ASPX page (Pretty sure error is here since the code in .js page works)
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="Scripts/Script.aspx.js"/>
</Scripts>
</asp:ScriptManager>
I also have some code lines in web.config to set keys SessionTimeout and SessionTimeoutWarning.
So, any idea on where's the glitch? Things used to run, now they won't.
EDIT
I'm using a script manager for a quick handling of the necessary ASP.NET AJAX components to enable partial postback. I need __doPostBack.
I found out if a js function is named pageLoad(), the function will activate when the page loads or when a partial postback. Just what I need.
So, asp.nex page is not loading pageLoad() function from .js.
Solved.
You can't set asp variables inside of javascript. So we have to set the variables in ASPX page, and then let javascript use them.
ASPX
<script type="text/javascript">
var millisecTimeOutWarning = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeoutWarning"]) * 60 * 1000 %>;
var millisecTimeOut = <%= int.Parse(System.Configuration.ConfigurationManager.AppSettings["SessionTimeout"]) * 60 * 1000 %>;
</script>
Then use them in .js file.
RadioButton rb;
Label lb;
while (reader.Read())
{
rb = new RadioButton(); **//radio buttuns created**
lb = new Label(); **// labels created**
lb.Text = reader[0].ToString(); *// each label's text assigned*
rb.Attributes.Add("OnClick", "getSelectedAuthor('"+lb.Text.ToString()+"')");
PlaceHolder1.Controls.Add(rb); *//when the radio clicked,function called*
PlaceHolder1.Controls.Add(lb); *// to set use the text of label*
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
conAuthorTbl.Close();
//innerthtml does not work for the purpose,//becuse I need to send//Labe2's text to other page, //when I use Response.Redirect(..), //there are no string coming //from Label2
<script language="javascript" type="text/javascript">
function getSelectedAuthor(text) {
document.getElementById("Label2").innerText = text;
}
</script>
//the text where I want to set the text
<div>
<asp:Label ID="Label2" runat="server" Text="" ></asp:Label>
</div>
Might I suggest you use something like knockout.js ? Its client side MVVM, you can use declarative bindings to achieve the task. I hope this helps.
http://knockoutjs.com/
try this:
<script language="javascript" type="text/javascript">
function getSelectedAuthor(text) {
document.getElementById("<%=Label2.ClientID%>").innerText = text;
}
</script>
This will work as long as the javascript is on the same aspx page.
If you need to wirk with it in external JS file, then you can create a mapping for your js file.
so you'll put something like this in your aspx page:
<script language="javascript" type="text/javascript">
var myElement_Label2 = getElementById("<%=Label2.ClientID%>");
etc...
</script>
and then in our external js file you can work just with those references like:
myElement_Label2.innerText = "something";
<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.