WebForms keeps showing Event validation error on post - c#

When I try to submit information from client to server, I receive Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/>. I've tried most of the suggestions in the answers and they don't seem to be helping.
At the top of the .aspx page in question, adding EnableEventValidation="false" does solve the issue. However, I would like to this to remain as set to true.
I've also added (!Page.IsPostBack) in the code behind and this is still causing issues.
Could it be the jQuery timpicker that's causing the issue by inputting values based on what the user selects?
Code behind .cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var DbHelper = new DbHelper();
listOfUsers.DataSource = DbHelper.UserList();
listOfUsers.DataBind();
}
else
{
string test = listOfUsers.SelectedValue;
string time = timePicker.Text;
string reason = ReasonForRemoval.Text;
}
}
}
.aspx file
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="xxxMyProjectNamexxx" EnableEventValidation="true"%>
<%--<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>--%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js' type='text/javascript'></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="/Scripts/jquery-ui-timepicker-addon.js"></script>
<link rel="stylesheet" href="/Styles/jquery-ui-timepicker-addon.css">
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('[id*=timePicker]').timepicker({
timeFormat: "hh:mm:ss"
});
});
</script>
<head>
<h2>
My App
</h2>
<p>
Enter relevant info
</p>
</head>
<body>
<form method="post">
<div>
<label for="UserName">User Name:</label>
<asp:DropDownList ID="listOfUsers" runat="server"></asp:DropDownList>
</div>
<br/><br/>
<table>
<tr>
<th>
<div>
<label for="Time">Time:</label>
<asp:TextBox ID="timePicker" runat="server"></asp:TextBox>
</div>
</th>
</tr>
</table>
<br/><br/>
<div>
<label for="Reason">Reaso:</label>
<br/>
<asp:TextBox ID="ReasonForRemoval" runat="server" TextMode="MultiLine" Rows="5" Width="400px" style="resize:none"></asp:TextBox>
</div>
<br/><br/>
<div>
<label> </label>
<input type="submit" value="Submit" class="submit" />
</div>
</form>
</body>
</asp:Content>
DbHelper.cs used to generate list
public class DbHelper
{
private EntityConnection entCon;
public DbHelper()
{
entCon = new EntityConnection(ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString);
}
public List<string> UserList()
{
List<string> userList = new List<string>();
using(SqlConnection conn = (SqlConnection)entCon.StoreConnection)
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [MyDatabase].[dbo].[users]";
using (SqlDataReader objReader = cmd.ExecuteReader())
{
if (objReader.HasRows)
{
while (objReader.Read())
{
userList.Add(Convert.ToString(objReader[0]));
}
}
}
}
return userList;
}
}
}

Related

html master page with data base sql server

plss help i have this problem:
Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
this is the master page code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link rel="shortcut icon" type="icon/x-icon" href="Main Images/favicon.ico" />
<link rel="stylesheet" type="text/css" href="MyStyle.css" />
<link href="style.css" rel="stylesheet" />
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body style="background-image: url('Main Images/background.jpg');">
<form id="form1" runat="server">
<div dir="rtl" style="background-color:#242020">
<audio src="songs/Jurassic Park Theme Song - Jurassic Park Theme Song.mp3" autoplay="" controls=""></audio><br /><br />
</div>
<div class="top">
<center> <img src="Main Images/logo.png" /></center>
<div>
<form name="login">
<span style="margin-top:25px;color:goldenrod;margin-left:3%;">Username<span style="margin-left:7px"><asp:TextBox type="text" id="userid" name="userid" style="color:fuchsia" placeholder="User Name" class="gg" runat="server"></asp:TextBox></span></span><br /><br />
<span style="margin-top:25px;color:goldenrod;margin-left:3%">Password<span style="margin-left:7px"><asp:TextBox class="gg" type="password" id="pswrd" name="pswrd" style="color:goldenrod" placeholder="Password" runat="server"></asp:TextBox><br /></span></span><p runat="server" id="ans" style="color:red"></p>
<span style="margin-left:4%"><asp:Button ID="Button1" onclick="Check_Click" class="login" runat="server" Text="Login" />
<input type="reset" class="cencel" value="Cancel"/></span><br /><br /><span style="margin-left:4.7%"><a class="button" href="Had Sign Up.aspx">sign up to HaD</a></span>
</form>
<script type="text/javascript">
function check(form) {
if(form.userid.value == "Oz Cohen" && form.pswrd.value == "guzguz8") {
window.open('HaDMan.aspx');
}
else {
if (form.userid.value != "Oz Cohen" && form.pswrd.value!= "guzguz8") { document.getElementById("ans").innerHTML = ("Eror Username and Password") }
if (form.userid.value == "Oz Cohen" && form.pswrd.value != "guzguz8") { document.getElementById("ans").innerHTML = ("Eror Password") }
if (form.userid.value != "Oz Cohen" && form.pswrd.value == "guzguz8") { document.getElementById("ans").innerHTML = ("Eror Username") }
}
}
</script>
</div>
<center>
<asp:Table ID="Table2" runat="server" style="margin-top:7px">
<asp:TableRow>
<asp:TableCell> <nav class="menu">
<ul class="clearfix">
<li>
<img style="margin-top:-20px"width="60" src="Main Images/lines.png" />
<ul class="sub-menu">
<li>My site page</li>
<li><a title="Got lost? Click here for the site map..." href="sitemap.aspx">Map of the site</a></li>
<li>Dinosuars Movies</li>
<li>Add new Dinosuars species</li>
<li>Had Site</li>
</ul>
</li>
</ul>
</nav></asp:TableCell>
<asp:TableCell>
<nav class="menu" >
<ul>
<li><span class="mainmenu">Home page</span></li>
</ul>
</nav>
</asp:TableCell>
<asp:TableCell>
<nav class="menu" >
<ul>
<li><span class="mainmenu">Carnivores</span></li>
</ul>
</nav>
</asp:TableCell>
<asp:TableCell>
<nav class="menu" >
<ul>
<li><span class="mainmenu">Vegetarian</span></li>
</ul>
</nav>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
this is the c# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class DinoMenu : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Check_Click(object sender, EventArgs e)
{
SqlConnection c;
string str = "Data Source =(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|\\DinoData.mdf;";
str += "Integrated Security= True";
c = new SqlConnection(str);
SqlCommand Cmd = new SqlCommand("SELECT COUNT(*) FROM [User] WHERE Pasword LIKE #Pasword AND Username LIKE #username;", c);
Cmd.Parameters.AddWithValue("#Pasword", pswrd.Text);
Cmd.Parameters.AddWithValue("#username", userid.Text);
c.Open();
int Userexist = (int)Cmd.ExecuteScalar();
c.Close();
if (Userexist > 0)
{
Response.Redirect("HaD.aspx", true);
}
else
{
ans.InnerText = "Eror Username and Password";
}
}
}
The problem you are having is because of this line:
<form name="login">
Delete this line and you will be ok.
If you have to gather the elements of your login form together, change it to a div instead
Explanation
HTML files cannot contain nested forms.
Every .aspx/.master file is already a form (That's the origin for the name Web Forms).
When you put a <form> inside one of these files you actually put your new form inside .NET's auto-created form

Repeater does not show data

As posted earlier , Here is my HTML :
<%# Page Title="" Language="C#" MasterPageFile="~/VendorMaster.master" AutoEventWireup="true" CodeFile="PastOrders.aspx.cs" Inherits="PastOrders" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<br />
<asp:Repeater ID="rptr" runat="server">
<HeaderTemplate>
<div class="col-lg-4 col-md-4 col-sm-4 mb">
<a href="VendorProfile.aspx">
<div class="twitter-panel pn">
<i class="fa fa-twitter fa-4x"></i>
</HeaderTemplate>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</ItemTemplate>
<FooterTemplate>
</div>
</a>
</FooterTemplate>
</asp:Repeater>
</asp:Content>
C# :
public partial class PastOrders : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["vendor"] != null)
{
if (!IsPostBack)
{
ArrayList values = new ArrayList();
values.Add(new Testing
{
Name = "Caterer"
});
values.Add(new Testing
{
Name = "Florist"
});
values.Add(new Testing
{
Name = "Cab Services"
});
rptr.DataSource = values;
rptr.DataBind();
}
}
else
{
Response.Redirect("VendorLogin.aspx");
}
}
public class Testing
{
public string Name { get; set; }
}
}
Now i want to generate 3 separate divs, with the Names on them as : "Caterer","Florist","Cab Services",etc.
Instead it is only generating one div with all the 3 names inside it .
I tried formatting it with the Header Template and the Footer Template where i put the parent divs and the anchor tag in the Header Template and the closing of the same in the Footer Template . Bt it doesn't produce the expected result still.
Now you do bind data, but you do not access your data within your repater. Change it to
<form id="form1" runat="server">
<asp:Repeater ID="rptr" runat="server" >
<ItemTemplate>
<div class="divStyle" id="divStyle">
<%# DataBinder.Eval(Container.DataItem, "Name") %>
</div>
</ItemTemplate>
</asp:Repeater>
</form>
and it should work!

Can't display results where the ending matches

I'm making a rhyme dictionary, and I have a database table with 3 coloumns, the user will search the database and the search keywords will search database where the ending of the word matches with the word in textbox.
When I enter some keyword into textbox
I get ERROR: Incorrect syntax near the keyword 'LIKE'.
This is how my database looks like
Here is how my aspx looks like:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Kafiye Dizini - Türkçe Kafiye Bulma Sözlüğü - Uyak Bulucu Sözlük - İstediğiniz harf ile biten kelimeleri bulan sözlük</title>
<meta name="description" content="İstediğiniz harfler ile biten kelimeleri bulmanızı sağlayan sözlük" />
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link href="style.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="top">
<div class="email">İletişim: fahrettinveysel#gmail.com</div>
</div>
<div class="leftcontainer">
</div>
<div class="middlecontainer">
<div class="title">Kafiye Dizini</div>
<div class="subtitle">İstediğiniz harf veya hece ile biten kelimeleri bulmanızı sağlayan sözlük</div>
<div class="searchcontainer">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
<div class="resultboxcontainer">
<div id="resultbox1" runat="server"></div>
<div id="resultbox2" runat="server"></div>
<div id="resultbox3" runat="server"></div>
</div>
<div class="idefix"></div>
</div>
<div class="rightcontainer">
<div class="ornekarama">
<div class="ornekaramabaslik">Örnek Arama</div>
<input type="text" class="ornekaramatextbox" value="rop" disabled="disabled" />
<div class="ornekaramasonuclar">filantrop<br />gardırop<br />hipermetrop<br />mikrop<br />mizantrop</div>
</div>
</div>
</div>
</form>
</body>
</html>
and this is my aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection cnn = new SqlConnection("Initial Catalog=kafiyedizini;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT kelime1,kelime2,kelime3 FROM kelimeler LIKE #arama", cnn);
cmd.Parameters.AddWithValue("#arama", "%" + TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
resultbox1.InnerHtml += dr.GetString(0);
resultbox2.InnerHtml += dr.GetString(1);
resultbox3.InnerHtml += dr.GetString(2);
}
}
cnn.Close();
}
else
{
resultbox1.InnerHtml += "please enter data";
}
}
}
The initial sql statement in your question should look like this
SELECT kelime1,kelime2,kelime3 FROM kelimeler where kelime1 LIKE #arama OR kelime2 LIKE #arama or kelime3 like #arama
You missed the where and the fields you want to use in your like statement.
to have each result in a separate 'box' you better investigate how a GridView works or a DataRepeater.
Closest in your initial code what could work, including support for handling null/emtpy values for one the fields returned, nicely filling the 3 resultboxes:
var f1 = dr.GetString(0);
var f2 = dr.GetString(1);
var f3 = dr.GetString(2);
if (!String.IsNullOrEmpty(f1))
resultbox1.InnerHtml += String.Format("<div>{0}</div>",f1);
if (!String.IsNullOrEmpty(f2))
resultbox2.InnerHtml += String.Format("<div>{0}</div>",f2);
if (!String.IsNullOrEmpty(f3))
resultbox1.InnerHtml += String.Format("<div>{0}</div>",f3);
You are missing WHERE part of the SQL query
Example:
SELECT * FROM test WHERE test.Id LIKE '%asd%'
I also think, dr.Read() executes PER ROW.
Hope this helps

How do I allow HTML tags to be submitted in a textbox in asp.net?

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.

my own little chat not working

I have made my own little chat. It it basicly a jQuery that reloads a div by inserting another .aspx site into it.
This is my .aspx site:
<%# Page Title="" Language="C#" MasterPageFile="~/holdOversigt.Master" AutoEventWireup="true"
CodeBehind="chat.aspx.cs" Inherits="HB.chat1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var reloadtime = 3000;
function load() {
$.ajax({
url: "chat-Content.aspx",
context: document.body,
success: function (data) {
document.getElementById('chat').innerHTML = data;
setTimeout('load()', reloadtime);
}
});
}
window.onload = function () {
setTimeout('load()', reloadtime);
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h1 style="text-align: center; color: #005da3; font-weight: bold">
<strong>Chat rum</strong></h1>
<div id="chat" class="fisk" style="width: 500px; height: 500px">
</div>
<br />
<asp:TextBox ID="txbMessege" runat="server"></asp:TextBox>
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click" />
</asp:Content>
THis is the site it inserts into the div:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="chat-Content.aspx.cs" Inherits="HB.chat_Content" %>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lbChat" runat="server" Rows="10" Width="400px"></asp:ListBox>
</div>
</form>
This is the sites codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HB
{
public partial class chat_Content : System.Web.UI.Page
{
grjenie31Entities gr;
protected void Page_Load(object sender, EventArgs e)
{
gr = new grjenie31Entities();
var query = from es in gr.chats
where es.id > ((from esh in gr.chats select esh.id).Max() - 15)
orderby es.timestamps descending
select es;
List<chat> list = new List<chat>();
foreach (chat chat in query)
{
list.Add(chat);
}
for (int i = 0; i < list.Count; i++)
{
lbChat.Items.Add("[" + list[i].timestamps + "] " + list[i].personID.ToString() + ": " + list[i].besked);
}
this.lbChat.SelectedIndex = this.lbChat.Items.Count - 1;
}
}
}
I can add new lines until it loads... but when the listbox is showed on the site it give me the follow error:
The state information is invalid for this page and might be corrupted.
Anybody got any idea what i can do about it??
It seems you inserted all page content even ViewState hidden tags.
I think it's better to clear your response and write your html tags which you needed in chat.
Response.Clear();
Response.ContentType = "text/plain";
Response.Write(GetChatResult());
Response.End();

Categories

Resources