In my winforms aplication I have a WebBrowser control named webBrowser1.
In code all I added is navigating to a page:
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://localhost:6489/Default.aspx");
}
The code for the page to which I navigate is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TableRowShow.Default" %>
<!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 type="text/javascript">
window.onload = function()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
function attach()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
var i = 1; // position of next tr to be shown
function addDest()
{
var trs = document.getElementById('travelTable').getElementsByTagName('tr');
if (trs[i] != null)
trs[i++].style.display = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="travelTable">
<tr>
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
</table>
<asp:HyperLink runat="server" ID="addDestination"
ClientIDMode="Static" NavigateUrl="javascript:;" >
Add Destination
</asp:HyperLink>
</form>
</body>
</html>
Seen in a browser like IE or Chrome the page looks like this:
Clicking on Add Destination anchor creates a new input:
The problem that I'm having with WebBrowser control is that it loads the page but the JavaScript doesn't work.
If I click on Add Destination nothing happens, even though the same page works well in Chrome or IE.
Placing a breakpoint and using:
webBrowser1.Document.InvokeScript("addDestination");
inside the Immediate window and then continuing to run the program activates the JavaScript in that function adding a new input.
Thanks for replies!
Try attaching the click handlers like this instead of using setAttribute in the onload and attach functions:
document.getElementById('addDestination').onclick = addDest;
You could try setting the ScriptErrorsSuppressed property to false to see whether any JavaScript errors occur.
Related
enter image description hereMy tutor gave me the following task: Create a form with 3 buttons(Save(Guardar) Edit(Editar) Delete(Eliminar) ).
But my real question is this:
I need to link my text box to my button allowing me to disable it and enable it at will but I can't conect them trough code.
PS:If you answer this question try as much as you can to be specific about the terms you use since I've started learning asp.net a few days ago.
enter image description here
First, you need to create the button event.
Double click to the button on your form, then the VB will create a button event automatically.
Now, you can code.
For i.e:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;//Disable textbox1 on the form
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="RedioButton.aspx.cs" Inherits="Shoping_Cart.RedioButton" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Enable Disable Textbox Using Jascript Radio Button Click</title>
<script type="text/javascript">
function EnableDisableTextBox() {
var status = document.getElementById('<%=rbtEnable.ClientID %>').checked;
if (status == true) {
document.getElementById('<%=TextBox1.ClientID %>').disabled = false;
} else {
document.getElementById('<%=TextBox1.ClientID %>').disabled = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Width="228px"></asp:TextBox>
<br />
<br />
<asp:RadioButton ID="rbtEnable" runat="server" Text="Enable" onclick="javascript:EnableDisableTextBox();" GroupName="1" />
<asp:RadioButton ID="rbtDisable" runat="server" Text="Disable" onclick="javascript:EnableDisableTextBox();" GroupName="1" />
</div>
</form>
</body>
</html>
I'm new to C# - ASP.NET and I'm trying to drop data ,from a filled form, from .aspx to .cshtml.
I made a form with three TextBoxes and a Button, a method for the "onClick". This method set the value of ViewData (name,date,user) with the values of the three TextBoxes. And I want to collect these value on the page targeted by the form.
I do not get any error but ViewData(name,date,user) seems to be empty.
Here's my code :
CSHTML
#{
ViewBag.Title = "Consulter";
}
#Html.Partial("MenuBar")
#Html.Partial("Connexion")
#ViewData["name"]
<style type="text/css">
...
</style>
...
<h2>...
ASPX
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<script language="C#" runat="server">
public void Ajouter(Object sender, EventArgs e)
{
ViewData["name"] = dateForm.Text;
ViewData["date"] = dateForm.Text;
ViewData["user"] = userForm.Text;
}
</script>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<meta name="viewport" content="width=device-width" />
<title>AjouterForm</title>
</head>
<body>
<h1>Ajouter un produit</h1>
<div>
<form id="form1" runat="server" action="Consulter" defaultbutton="bouton1" method="get">
<div>
<asp:TextBox placeholder="Name" runat="server" ID="nameForm"/></br>
<asp:TextBox placeholder="Date" runat="server" ID="dateForm"/></br>
<asp:TextBox placeholder="User" runat="server" ID="userForm"/></br>
<asp:Button runat="server" text="Envoyer" ID="bouton1" onClick="Ajouter"/>
<asp:Label runat="server" ID="label1" />
</div>
</form>
</div>
</body>
</html>
If you know how to solve it or if you have another way to do it, it would be amazing :)
Thank you in advance.
I have a .NET application with the following aspx code:
<%# Page Language="C#" AutoEventWireup="True" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default"%>
<%# Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>
<%# Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik"%>
<!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" >
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ToolkitScriptManager>
<table>
<tr>
<td>
<asp:RadioButtonList ID="rblTest" runat="server" AutoPostBack="True"
onselectedindexchanged="rblTest_SelectedIndexChanged">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:PlaceHolder ID="ph1" runat="server" Visible="False">
Some text
</asp:PlaceHolder>
</td>
</tr>
</table>
</form>
</body>
</html>
I then have a C# method as follows:
protected void rblTest_SelectedIndexChanged(object sender, EventArgs e)
{
if (rblTest.SelectedValue == "2")
ph1.Visible = true;
else
ph1.Visible = false;
}
Below is where the crash occurred. It crashes any time I use a control that has autopostback=true. I use the same syntax on about 15 other forms and those all work just fine. Am I missing a property somewhere or is there something wrong with my method? I originally had an UpdatePanel around the controls and I plan on adding it again, but I need to get the postback working first.
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['Default'];
if (!theForm) {
theForm = document.Default;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit(); <-----Crashed at this line.
}
}
//]]>
</script>
What am I missing or is there some common mistake that I may have made somewhere? Thanks in advance for your help.
Your __doPostBack script is trying to submit a form with id "Default" (see document.forms["Default"] line; yet your markup shows a form with id "form1" so it's clear why it doesn't work: the __doPostBack function is not finding the form and calling theForm.submit() fails.
You can attempt to fix it by renaming the form to use the id "Default" since I don't think you can control the way the __doPostBack script is generated.
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.