This is my page code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ProductType.aspx.cs" Inherits="Application.ProductType" MasterPageFile="~/Main.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<script type="text/javascript">
function getMainTable() { return document.getElementById("<%= ProductGridMain.ClientID %>"); }
</script>
<script type="text/javascript" src="JavaScripts/ProductType.js"></script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/Services/ProductTypeService.svc" />
</Services>
</asp:ScriptManager>
<asp:Label ID="ProductGridMain" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="AddNewItemBtn" CssClass="Btn" runat="server" Text="New" OnClientClick="NewAddBtn(); return false;" />
</asp:Content>
This is the ProductType.js file:
$(document).ready(function() {
var counter = "fast";
ProductTypeService.GetMainGridProductTypeHtml(counter, ResultLoadTableMainGridHtml, ErrorLoadTableMainGridHtml);
});
function ResultLoadTableMainGridHtml(html) {
//debugger;
var tblMainGrid = getMainTable();
if (tblMainGrid != null && html != null && html != "null" && html != "" && html != " ") {
tblMainGrid.innerHTML = html;
}
}
function ErrorLoadTableMainGridHtml(html) {
alert("Error");
}
function NewAddBtn() {
//debugger;
var counter = "test";
ProductTypeService.GetMainGridProductTypeHtml(counter, ResultLoadTableMainGridHtml, ErrorLoadTableMainGridHtml);
}
The service method returns html code of main grid, then in javascript I insert it into label.
When I click on button everything works correctly like I suppose, but page is reloading. How do I call the service method on button click without page reloading?
Why not use HTML button instead of ASP.NET button - that way you can indicate that you don't need submit behavior. For example,
<input type="button" id="AddNewItemBtn" class="Btn" runat="server" value="New" onclick="NewAddBtn()" />
You may eliminate runat="server" if you don't need to refer to the button in the server code.
Related
Trying to reload an iframe after C# has modified its attributes. Here's the page:
<script type="text/javascript">
function reloadFrame(Map) {
document.getElementById(Map).contentDocument.location.reload(true);
}
</script>
<asp:TextBox ID="TextBox1" placeholder="Zip code" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Find locations" onclick="Button1_Click" />
<iframe id="Map" runat="server"></iframe>
And when the button is clicked it runs this:
var zipCode = TextBox1.Text;
Map.Attributes.Add("src", "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipCode);
browser.Document.InvokeScript("reloadFrame", new[] { "Map" });
However the line to reload the iframe doesn't work. Any ideas?
How about setting the src for the iFrame via inline code?
<iframe id="Map" runat="server" src='<%= (TextBox1.Text == "" ? "" : "https://www.google.com/maps/preview#!q=gnc+near%3A+" + zipCode) %>'></iframe>
I'm developing an web user control for that i need to set some properties at page load (client side page load). My control works fine with one instance on page.
But when i need multiple instance of that control on same page.Page load event shows effects only on last control.
My control
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControlLoadTest.ascx.cs" Inherits="WebUserControlLoadTest" ClientIDMode="Predictable" %>
<link rel="stylesheet" href="GridViewCSSThemes/YahooGridView.css" type="text/css" media="screen" />
<script runat="server" type="text/C#">
static Int16 _count;
public static Int16 count
{
get { return _count++; }
}
</script>
<script type="text/javascript">
function pageLoad() {
document.getElementById('<%= Hidden_RowIndex.ClientID%>').value = '<%= count%>';
document.getElementById('<%= txtUC.ClientID%>').value = "Count : " + document.getElementById('<%= Hidden_RowIndex.ClientID%>').value;
}
</script>
<asp:HiddenField ID="Hidden_RowIndex" Value="" runat="server" />
<asp:TextBox ID="txtUC" CssClass="tb10" Enabled="false" runat="server"></asp:TextBox>
Use control on aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ContextMenuTest.aspx.cs" Inherits="ContextMenuTest" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%# Register TagPrefix="uc1" TagName="UCTest" Src="~/WebUserControlLoadTest.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Java Script Load Test</title>
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1" EnablePageMethods="true" />
<table style="padding:1%;width:100%;">
<tr>
<td>
<uc1:UCTest runat="server" ID="UCTest1"/>
</td>
</tr>
<tr>
<td>
<uc1:UCTest runat="server" ID="UCTest2"/>
</td>
</tr>
</table>
</form>
</body>
After execution result will be Count - 0 in first Control and Count - 1 in Second.
But it shows 1 Control blank and second with Control -1 text.
Can any one tell me how can i make different instance of java-script page-load event in multi instance web user control.
The problem is
static Int16 _count;
public static Int16 count
{
get { return _count++; }
}
If you declare your control multiple times, then you override the counter each time the control is rendered.
You need a smarter Javascript, for examle, add a class on the control wrapper inside WebUserControlLoadTest.ascx something like
<div class="myControl">
<asp:HiddenField ID="Hidden_RowIndex" Value="" runat="server" />
<asp:TextBox ID="txtUC" CssClass="tb10" Enabled="false" runat="server">
</asp:TextBox>
</div>
and at the top of the aspx page you can have this:
$(document).ready(function(){
var count = 0;
$("myControl input:hidden").each(function(){$(this).value = count++});
});
First, I want to let everyone know that I am using an aspx engine not a Razor engine.
I have a table within a form. One of my textbox contains html tags like
</br>Phone: </br> 814-888-9999 </br> Email: </br> aaa#gmail.com.
When I go to build it it it gives me an error that says:
A potentially dangerous Request.Form value was detected from the client (QuestionAnswer="...ics Phone:<br/>814-888-9999<br...").
I tried the validation request="false" but it did not work.
I am sorry I didn't add my html code for you to look at so far. I am pulling some question up where I can edit it, if need be.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
EditFreqQuestionsUser
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("#freqQuestionsUserUpdateButton").click(function () {
$("#updateFreqQuestionsUser").submit();
});
});
</script>
<h2>Edit Freq Questions User </h2>
<%Administrator.AdminProductionServices.FreqQuestionsUser freqQuestionsUser = ViewBag.freqQuestionsUser != null ? ViewBag.freqQuestionsUser : new Administrator.AdminProductionServices.FreqQuestionsUser(); %>
<%List<string> UserRoleList = Session["UserRoles"] != null ? (List<string>)Session["UserRoles"] : new List<string>(); %>
<form id="updateFreqQuestionsUser" action="<%=Url.Action("SaveFreqQuestionsUser","Prod")%>" method="post" onsubmit+>
<table>
<tr>
<td colspan="3" class="tableHeader">Freq Questions User Details <input type ="hidden" value="<%=freqQuestionsUser.freqQuestionsUserId%>" name="freqQuestionsUserId"/> </td>
</tr>
<tr>
<td colspan="2" class="label">Question Description:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionDescription" value=" <%=freqQuestionsUser.questionDescription%>" />
</td>
</tr>
<tr>
<td colspan="2" class="label">QuestionAnswer:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionAnswer" value="<%=freqQuestionsUser.questionAnswer%>" />
</td>
</tr>
<tr>
<td colspan="3" class="tableFooter">
<br />
<a id="freqQuestionsUserUpdateButton" href="#" class="regularButton">Save</a>
Cancel
</td>
</tr>
</table>
</form>
</asp:Content>
before the page is submitted you need to html encode the textbox's value, with window.escape(...)
If you need the un-escaped text on the server side then use HttpUtility.UrlDecode(...) method.
very quick sample:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SO.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function makeSafe() {
document.getElementById('TextBox1').value = window.escape(document.getElementById('TextBox1').value);
};
function makeDangerous() {
document.getElementById('TextBox1').value = window.unescape(document.getElementById('TextBox1').value);
}
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="makeSafe();">
<div>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Rows="10" ClientIDMode="Static"></asp:TextBox>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
<script>
makeDangerous();
</script>
</body>
</html>
Make these changes to your code:
<script type="text/javascript">
$(document).ready(function () {
makeDangerous();
$("#freqQuestionsUserUpdateButton").click(function () {
makeSafe();
$("#updateFreqQuestionsUser").submit();
});
});
// Adding an ID attribute to the inputs you want to validate is simplest
// Better would be to use document.getElementsByTagName and filter the array on NAME
// or use a JQUERY select....
function makeSafe() {
document.getElementById('QuestionAnswer').value = window.escape(document.getElementById('QuestionAnswer').value);
};
// In this case adding the HTML back to a textbox should be 'safe'
// You should be very wary though when you use it as actual HTML
// You MUST take steps to ensure the HTML is safe.
function makeDangerous() {
document.getElementById('QuestionAnswer').value = window.unescape(document.getElementById('QuestionAnswer').value);
}
</script>
Decorate your controller action with the [ValidateInput] attribute:
[ValidateInput(false)]
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
...
}
Client JavaScript:
function codificarTags()
{
document.getElementById('txtDescripcion').value = document.getElementById('txtDescripcion').value.replace(/</g,'<').replace(/>/g,'>');
}
<form id="form1" runat="server" onsubmit="codificarTags();">
Server:
protected void Page_Load(object sender, EventArgs e)
{
txtDescripcion.Text = txtDescripcion.Text.Replace(#"<", #"<").Replace(#">", #">");
}
I would suggest using the AjaxControlToolkit's HTML Editor. I'm implementing that now. If you're textbox is multi-line and big enough to accommodate HTML, why not just bump it up to an HTML editor. Your user will be happier too.
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HTMLEditor/HTMLEditor.aspx
Using html in textbox is not a good practice, maybe use linebreaks (Environment.NewLine) or \r\n instead of br ?
.NET Reference
Example (in C#) :
textBox1.Multiline = true;
textBox1.Text = "test" + Environment.NewLine + "test2";
I took a bit of a different approach. I wanted to use html textboxes widely across my application. I made a user control which would avoid editing the javascript every time I added a new control. My entire control is very custom but the heart of the html handling is as seen below.
The UserControl markup has some simple javascript to escape and unescape the textbox.
<script type="text/javascript">
function UnescapeControl(clientId) {
$('#' + clientId).val(window.unescape($('#' + clientId).val()));
}
function EscapeAllControls() {
var escapeControList = JSON.parse('<%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(EscapeControlList) %>');
for (var i = 0; i < escapeControList.length; i++)
EscapeControl(escapeControList[i]);
}
function EscapeControl(textClientId) {
document.getElementById(textClientId).value = window.escape(document.getElementById(textClientId).value);
}
</script>
<asp:TextBox ID="Txt_SavableText" CssClass="form-control" Width="100%" runat="server" ></asp:TextBox>
The code behind is responsible for escaping the controls before the post back using RegisterOnSubmitStatement and unescaping them using RegisterStartupScript after the post back.
public partial class SavableTextBox : System.Web.UI.UserControl
{
public List<string> EscapeControlList
{
get
{
if (Session["STB_EscapeControlList"] == null)
Session["STB_EscapeControlList"] = new List<string>();
return (List<string>)Session["STB_EscapeControlList"];
}
set { Session["STB_EscapeControlList"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (EscapeHtmlOnPostback && !EscapeControlList.Contains(GetClientId()))
EscapeControlList.Add(GetClientId());
// When using a script manager, you should use ScriptManager instead of ClientScript.
if (EscapeHtmlOnPostback)
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "UnescapeControl_" + GetClientId(), "UnescapeControl('" + GetClientId() + "');", true);
// Ensure we have our escape script called before all post backs containing escapable controls.
// This is like calling OnClientClick before everything.
if (EscapeControlList != null && EscapeControlList.Count > 0)
this.Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "SaveableTextBoxEscaper", "EscapeAllControls();");
}
public string Text
{
get
{
return Txt_SavableText.Text;
}
set
{
Txt_SavableText.Text = value;
}
}
public string GetClientId()
{
return Txt_SavableText.ClientID;
}
}
Now we can use it anywhere like this while setting EscapeHtmlOnPostback="True".
<%# Register TagPrefix="STB" TagName="SavableTextBox" Src="~/SavableTextBox.ascx" %>
<STB:SavableTextBox ID="Txt_HtmlTextBox" EscapeHtmlOnPostback="True" runat="server" />
Note, when we access Txt_HtmlTextBox.Text during the post back it will already be escaped for us.
Just getting started with AJAX and tried a simple example in the microsoft 70515 book. However, the code doesnt seem to work, and I can't figure out why not - as it seems ok.
Edit: for some reason a part of the code did not get posted, (even as I am writing this now the code looks weird, it is like I can't post all my code??) I've fixad that now- but what's up with the down vote? I cant really see what is stupid about my question. Please explain.
Hoping somebody can spot the problem and help me out here :)
Markup .aspx:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="AjasxTest._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
<br /><br />
<script type="text/javascript">
function ClientCallbackFunction(args) {
window.LabelMessage.innerText = args;
}
</script>
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="FooterContent">
<asp:DropDownList ID="DropDownListChoice" runat="server" OnChange="MyServerCall(DropDownListChoice.value)">
<asp:ListItem>Choice 1</asp:ListItem>
<asp:ListItem>Choice 2</asp:ListItem>
<asp:ListItem>Choice 3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="LabelMessage" runat="server"></asp:Label>
</asp:Content>
Code-behind:
namespace AjasxTest
{
public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
string callbackRef = Page.ClientScript.GetCallbackEventReference(this, "args", "ClientCallbackFunction", "");
string callbackScript = String.Format("function MyServerCall(args) {{{0};}}", callbackRef);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"MyServerCall", callbackScript, true);
}
public string GetCallbackResult()
{
return _callbackArgs;
}
string _callbackArgs;
public void RaiseCallbackEvent(string eventArgument)
{
_callbackArgs = eventArgument;
}
}
}
Your JS function is called ClientCallbackFunction but you're calling it in the DropDownList OnChange event as MyServerCall.
<script type="text/javascript">
function ClientCallbackFunction(args) {
window.LabelMessage.innerText = args;
}
</script>
...
<!-- Call correct JS function in OnChange -->
<asp:DropDownList ID="DropDownListChoice" runat="server" OnChange="ClientCallbackFunction(DropDownListChoice.value)">
...
Your code is pretty close, however the problem is in the fact you are trying to access ServerSide objects (such as Label and DropDownList) from the client side.
For example, an asp:Label control, when rendered to a web browser on the client side, is actually an HTML div. The ID of the label in Visual Studio might be "LabelMessage", but depending on the layout of your page and controls, the ID on the client side (i.e., for the user that clicks view source in FireFox or IE) could be generated as "FooterContent_LabelMessage1" or something like that.
ASP.net controls do come with a property you can use to access the generated ID in JavaScript, which can be accessed by YourControl.ClientID.
I've made these changes to your code and have been able to make it work. I also added some null reference checking in the JavaScript to ensure the objects we are trying to reference, in fact, exist. Note I've tested this in a blank, brand new ASP.net forms application.
Here's the updated code for the Default page (front end):
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="TheAnswer._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<br />
<script type="text/javascript">
function ClientCallbackFunction(args) {
var labelMessage = $get("<%= LabelMessage.ClientID %>");
if (labelMessage) {
labelMessage.innerText = args;
}
}
function MyServerCallWrapper() {
var dropDown = $get("<%= DropDownListChoice.ClientID %>");
if (dropDown) {
MyServerCall(dropDown.value);
}
}
</script>
</asp:Content>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="FooterContent">
<asp:DropDownList ID="DropDownListChoice" runat="server" onchange="javascript:MyServerCallWrapper();">
<asp:ListItem>Choice 1</asp:ListItem>
<asp:ListItem>Choice 2</asp:ListItem>
<asp:ListItem>Choice 3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="LabelMessage" runat="server"></asp:Label>
</asp:Content>
Note the $get() function is a built-in ASP.net (not JQuery) function that is shorthand for document.getElementById() - they are interchangeable and do exactly the same thing. You need to pass the ClientID in quotes to either of these methods in JavaScript, and it will return a reference to the object you are trying to access.
Just for fun, I modified one of the back-end functions so you know that the call back was processed on the server:
public string GetCallbackResult()
{
return _callbackArgs + " from the server!";
}
And voila! this works for me -
I hope it works for you too and I hope it's clear where the problem was; most of your example was working / setup perfectly.
I want to call jQuery function from server.
The server side button that calls function is inside an UpdatePanel.
this is server side function :
//Button Click handler (It is inside Updatepanel)
string ScriptName = null;
ScriptName = "function pageLoad(sender, args) { if (args.get_isPartialLoad()) {DisplayMessage(); }}";
ScriptManager.RegisterStartupScript(this, GetType(), "DisplayMessage", ScriptName, true);
and this is client side function :
<script type="text/javascript">
function DisplayMessage() {
//Alert("Called");
}
</script>
It doesn't work.
What's wrong ? (Is my question and problem clear?)
That's weird, as the following works perfectly fine for me:
<%# Page Language="C#" %>
<script type="text/c#" runat="server">
protected void BtnTrigger_Click(object sender, EventArgs e)
{
string script = "function pageLoad(sender, args) { if (args.get_isPartialLoad()) {DisplayMessage(); }}";
ScriptManager.RegisterStartupScript(
this,
GetType(),
"DisplayMEssage",
script,
true
);
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function DisplayMessage() {
alert('called');
}
</script>
</head>
<body>
<form id="Form1" runat="server">
<asp:ScriptManager ID="scm" runat="server" />
<asp:LinkButton
ID="BtnTrigger"
runat="server"
Text="Trigger"
OnClick="BtnTrigger_Click"
/>
<asp:UpdatePanel ID="up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger
ControlID="BtnTrigger"
EventName="Click"
/>
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
Also do you really need all the complex script, why not simply use string script = "DisplayMessage();";?
create a display:none div in the page. Put it in update panel. This will not disturb your design. to execute every sclient side script in page
<div id="scriptContainer" runat="server" style="display:none;"></div>
then paste your js in it on an event.
scriptContainer.innerHTML = "<script type=text/javascript>DisplayMessage();</script>";
hope it helps.