Are there any potential side-effects to below solution to injecting JavaScript from the content of an updated UpdatePanel?
The code for the UpdatePanel looks sort of like this:
<asp:UpdatePanel>
<asp:PlaceHolder ID="pnlScriptContent" Visible="false" runat="server">
<script id="script-content">
alert('Script was loaded correctly!');
</script>
</asp:PlaceHolder>
<asp:Button OnClick="ButtonClick" OnClientClick="LoadScript()" />
</asp:UpdatePanel>
The code-behind on the click of the Button shows the Panel pnlScriptContent.
protected void ButtonClick(object sender, EventArgs args)
{
pnlScriptContent.Visible = true;
}
The JavaScript-code looks like this:
var LoadScript = function() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) {
eval($('#script-content').html());
};
}
I've seen other solutions to inject JavaScript after an UpdatePanel updates, but nothing that allows the injection of JavaScript inside script-tags in the content.
Is there a reason to this? Security maybe?
You can use RegisterClientScriptBlock static method of the ScriptManager class
Related
So I need to make a list of items with delete buttons delete their specific item. I set up an Ajax call and a webmethod in the codebehind, as I've done before in this site, but for some reason it returns the page's entire HTML again, rather than executing the webmethod and returning what I'd like it to return. Frustrated I tried to use a pagemthod instead, but it returns the same result without executing my webmethod at all.
Interestingly I have this working on several other pages already, and basically copy and pasted what I had, but for some reason on this page it doesn't work. Which means I know that it's not an issue with the server or any httpModules in the web config. I've tried the solutions I used before on my site, which were:
form1.Action = Request.RawUrl; at the top of the Page_Load function in codebehind, because of URL rewriting
PageMethods.set_path("~/Inbox.aspx"); in the javascript for the same reason as above
The below was a proposed solution to go in the web.config, but it just causes the whole server to 500. I don't see how it could help anyway though since pagemethods and ajax work on other pages on my site.
<system.web>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
I've stripped the code down to almost nothing to make it function as basically as possible, so I'm certain there are no errors. The code always executes as successful anyway.
Here's the full code, just for context:
HTML/JS:
<form id="form1" runat="server" style="text-align:left">
<asp:ScriptManager runat="server" ID="mailSM" EnablePageMethods="true" EnablePartialRendering="true" ClientIDMode="Static" ></asp:ScriptManager>
<input runat="server" id="maillist" type="hidden" value="" />
<input runat="server" id="inboxhf" type="hidden" value="1" />
<div id="mail-collection" class="main-container">
<a id="back" class="buttons" href="/">back</a><a class="buttons" href="/sendmail">send new mail</a><a id="box" class="buttons" href="/outbox">your sent mail</a>
</div>
<script type="text/javascript">
function DeleteMail(mailID, fromID, toID) {
let pagepath = window.location.pathname.substr(1);
PageMethods.set_path("Mailbox.aspx");
PageMethods.DeleteMailCB(fromID, toID, pagepath, mailID, OnSuccess, OnError);
}
function OnSuccess(response) {
alert(response);
location.reload();
}
function OnError(response) {
alert("e" + response);
//OnSuccess();
}
</script>
</form>
C#:
[WebMethod]
public static void DeleteMail(string fromID, string toID, string pagepath, string mailID)
{
DB.TestForSomething();
//above just does a basic INSERT straight into a test table in the
//database. since nothing is being inserted, I know this webmethod
//isn't getting used at all.
return;
}
Not sure what I should do from here since the solutions that I've found work on the other pages, but not this one. Thanks in advance!
Here I am hitting my method. Please see comments in the code.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="FredWebForm.WebForm4" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
function DeleteMail(mailID, fromID, toID) {
let path = window.location.pathname.substr(1);
//"inbox" or "outbox"
//changed path for me
//PageMethods.set_path("~/Inbox.aspx");<---did not work
//What you had did not work
PageMethods.set_path(path);
PageMethods.DeleteMail(fromID, toID, path, mailID, OnSuccess, OnError);
}
function OnSuccess(response) {
alert(response);
//remarked out initially
location.reload();
}
function OnError() {
//OnSuccess();
}
$(function () {
$("#theButton").click(function () {
DeleteMail(12, 14, 16);
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="sm" EnablePartialRendering="true" EnablePageMethods="true">
</asp:ScriptManager>
<div>
<input type="button" value="Go" id="theButton" />
</div>
</form>
</body>
</html>
Code behind
//I am using WebForm4, but you can use a different page name
public partial class WebForm4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
form1.Action = Request.RawUrl;
}
[WebMethod]
public static string DeleteMail(string fromID, string toID, string pagepath, string mailID)
{
//DB.TestForSomething();
//above just does a basic INSERT straight into a test table in the
//database. since nothing is being inserted, I know this webmethod
//isn't getting used at all.
return "SomeData";
}
}
To anyone who stumbles upon this from the future, who knows they did everything correctly but still has it refuse to work: I found, way at the bottom of my web.config, buried beneath all of my URL rewrites, a small little <modules><remove name=""></modules> rule that disabled the ScriptModule.
Not sure how that got there, but apparently it did. As soon as I removed it, the site's webmethods started working again. I feel stupid that I was stuck on this for a whole week.
So here's what I'm trying to accomplish:
I have a client facing page that loads, and when that happens I automatically run a series of 4 quick tests, if any of those tests fail I update the HCresults variable.
.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script language="javascript" src="script/XmlHttp.js?vers=<%=VersionInfo %>" type="text/javascript"></script>
<script src="client_scripts/JQuery/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
var HCresults = "";
</script>
</asp:Content>
I want to access the value of HCresults after the page finishes loading from my code behind page. Is there a way to do this?
You can write a webmethod in your code behind;
pseudo code:
public static var HCresultsCS;
[webmethod]
public static void grabHCresults(var HCresultsfromJS)
{
HCresultsCS= HCresultsfromJS;
}
make an AJAX post to this webmethod with HCresults you're setting on a test failure as parameter;
Access the HCresultsCS from CS now. Check for nulls! I can't comment
This link might be helpful:
http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Unfortunately not using JS, you can store the value in a hiddenfield however to retrieve in C#. Make sure that you set the attribute runat = "server" for the control. I should also mention you'll use element.value = value to assign the value.
How to execute JavaScript of Content page while using Update panel ?
something i found after browsing for answer is this.
Instead of putting your jQuery code inside of $(document).ready(), put it inside
function pageLoad(sender, args) {
}
but i don't understand that? and My requirement is within the content page!
just put your javascripts code in UpdatePanel
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- your code -->
<script src="/js/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("a").on("click", function () {
alert("it's work!");
});
});
</script>
</ContentTemplate>
</asp:UpdatePanel>
I need to add specific js files to the page.
On Page_Load, I'm trying this:
ClientScript.RegisterClientScriptInclude("MyTab", HttpRuntime.AppDomainAppPath + "\\scripts\\" + tabName);
It doesn't working.
You can try this solution that will always work. use:
Page.Header.Controls.Add(new LiteralControl("<script type='text/javascript' src='script.js'></script>"));
You can simply do this without the need to load it in the code-behind:
<asp:ScriptManager ID="sm" runat="server">
<Scripts>
<asp:ScriptReference Path="./script.js" />
</Scripts>
</asp:ScriptManager>
If you want to add or change the script file at runtime, just leave the ScriptManager in your mark-up and access it like this:
ScriptManager sm = ScriptManager.GetCurrent(Page);
if (Smgr != null)
{
ScriptReference sr = new ScriptReference();
sr.Path = "~/Scripts/Script.js";
sm.Scripts.Add(sr);
}
Make sure you're not using "MyTab" anywhere else to register scripts. It's a key for the script.
Also HttpRuntime.AppDomainAppPath will return the physical path, which makes me think it could return for example C:\Program Files\... which won't work for people visiting the site.
Maybe try:
ClientScript.RegisterClientScriptInclude("MyTab", Page.ResolveClientUrl("~\\scripts\\" + tabName));
I have a site where 6 css files are linked, But in a page i need to use only 3 css files. My developers are using master page in .net, so they don't want to change that. So, my question is: Is there any way I can skip few css files which is linked?
It is not very 'elegant' but you can use a jQuery script to manipulate and remove the link:
<script type="text/javascript">
$(document).ready(function () {
$("link[type='text/css']").remove();
});
</script>
You can use jQuery selector to refine the search. I.e.
$("link[href='Styles/Site.css']").remove();
Another solution (doesn't need jQuery) is adding a configuration property to the master page like this:
Site.Master.cs
private bool _IncludeOtherCss = true;
public bool IncludeOtherCss {
get { return _IncludeOtherCss; }
set { _IncludeOtherCss = value; }
}
Site.Master (head section)
<%if (IncludeOtherCss)
{ %>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<%} %>
Other page:
protected void Page_Init(object sender, EventArgs e)
{
(Master as SiteMaster).IncludeOtherCss = false;
}