Add html content to Microsoft SQL Server database asp net - c#

I want to add html content into a SQL Server database.
For example, on a label it is shows location coordinates, and after button click it will be added in SQL Server. I have gone so far but every time I click on the button it is added in the database empty, not coordinates.
I will give the source code...
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="tripmeter" runat="server">
<p runat="server">
Starting Location (lat, lon):<br />
<span id="startLat" runat="server"></span>°, <span id="startLon" runat="server"></span>°
</p>
<p runat="server">
Current Location:<br />
<label id="currentLat" runat="server"></label>°, <span id="currentLon" runat="server"></span>°
</p>
<p runat="server">
Distance from starting location:<br />
<span id="distance" runat="server">0</span> km
</p>
<input id="Button1" type="button" value="button" runat="server" onserverclick="MySubmitHandler" />
</div>
<script>
window.onload = function () {
var startPos;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
startPos = position;
document.getElementById("startLat").innerHTML = startPos.coords.latitude;
document.getElementById("startLon").innerHTML = startPos.coords.longitude;
}, function (error) {
alert("Error occurred. Error code: " + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from locaton provider)
// 3: timed out
});
navigator.geolocation.watchPosition(function (position) {
document.getElementById("currentLat").innerHTML = position.coords.latitude;
document.getElementById("currentLon").innerHTML = position.coords.longitude;
document.getElementById("distance").innerHTML =
calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
position.coords.latitude, position.coords.longitude);
});
}
};
function calculateDistance(lat1, lon1, lat2, lon2) {
var R = 6371; // km
var dLat = (lat2 - lat1).toRad();
var dLon = (lon2 - lon1).toRad();
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
</script>
</form>
</body>
</html>
Default.aspx.cs
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;
using System.Configuration;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void MySubmitHandler(object sender, EventArgs args)
{
try
{
SqlConnection lidhje = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
lidhje.Open();
string fut = "insert into Test (lat) values (#lat)";
SqlCommand komande = new SqlCommand(fut, lidhje);
komande.Parameters.AddWithValue("#lat", currentLat.InnerText);
komande.ExecuteNonQuery();
Response.Write("Success");
lidhje.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}

Set datatype Text in your database;
eg:
create table temp(
linkId int(10) PRIMARY KEY,
htmlValue Text(200) NULL); // this will store your data in HTML format.

Related

How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database?

How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database?
Because I ask question at link but I learn asp:Repeater tag article have to declare Microsoft SQL Server database in DataBind article.
I ask question to solve "How to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database."
Good news : I have answer to use asp:Repeater tag and then use data-binding expressions without declare Microsoft SQL Server database.
My full source code.
https://github.com/doanga2007/CheckLoopQR
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckLoopQR.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.6.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:CheckBox ID="checkAll" runat="server" Font-Size="Large"/><asp:Label id="checkTextAll" runat="server" Font-Size="Large"></asp:Label><br /><br />
<asp:CheckBoxList ID="CheckBox1" runat="server" Border="1"
BorderColor="LightGray" Font-Size="Large"></asp:CheckBoxList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace CheckLoopQR
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.checkTextAll.Text = " Check All";
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
long num = Convert.ToInt64(code);
int i;
for (i = 1; i < 4; i++)
{
num += i;
CheckBox1.Items.Add(new ListItem(" " + num));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
if (CheckBox1.SelectedItem == null)
{
Response.Redirect("Default.aspx");
}
string[] texture = { "Selected Item Text1 : ", "Selected Item Text2 : ", "Selected Item Text3 : " };
int a = 0;
foreach (ListItem listItem in CheckBox1.Items)
{
if (listItem.Selected)
{
a++;
string code = listItem.Text;
CheckBox1.Visible = false;
checkAll.Visible = false;
checkTextAll.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
Label lblvalues = new Label();
lblvalues.Text += texture[a-1] + listItem.Text;
lblvalues.Font.Size = FontUnit.Large;
Label lblvalues2 = new Label();
lblvalues2.Text += texture[a-1] + listItem.Text;
lblvalues2.Font.Size = FontUnit.Large;
Label lblvalues3 = new Label();
lblvalues3.Text += texture[a-1] + listItem.Text;
lblvalues3.Font.Size = FontUnit.Large;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues2);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
PlaceHolder1.Controls.Add(lblvalues3);
PlaceHolder1.Controls.Add(new HtmlGenericControl("br"));
}
}
else
{
//do something else
}
}
}
}
}

How coding to can for loop asp:RadioButton tag same as for loop asp:Label tag?

How coding to can for loop asp:RadioButton tag same as for loop asp:Label tag , Because I can for loop asp:Label tag with tutorial website
https://asp-net-example.blogspot.com/2008/12/aspnet-for-loop-example-using-for-loop.html
but I can't for loop asp:RadioButton tag same as for loop asp:Label tag.
Sample code at the bottom.
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="QRCode_Demo.QRCode" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder><br /><br />
<asp:RadioButton id="CheckBox1" runat="server" Font-Size="Large"></asp:RadioButton><asp:Label ID="checker" runat="server" Font-Size="Large"></asp:Label>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
namespace QRCode_Demo
{
public partial class QRCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
for (int i = 1; i < 11; i++)
{
checker.Text += " " + code + "<br>";
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
CheckBox1.Visible = false;
checker.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
}
}
Good News , I found answer to can for loop asp:RadioButton tag same as for loop asp:Label tag (Answer code found at link).
Answer code at the bottom.
Default.aspx (HTML Code)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="QRCode_Demo.QRCode" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>QR Code Generator</h2>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Please Input Data</label>
<div class="input-group">
<asp:TextBox ID="txtQRCode" runat="server" CssClass="form-control"></asp:TextBox>
<div class="input-group-prepend">
<asp:Button ID="btnGenerate" runat="server" CssClass="btn btn-secondary" Text="Generate" OnClick="btnGenerate_Click" />
</div>
</div>
</div>
</div>
</div>
<asp:Button ID="btnSelect" runat="server" CssClass="btn btn-secondary" Text="Display Text" OnClick="btnSelect_Click" /><br /><br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder><br /><br />
<asp:RadioButtonList
ID="CheckBox1"
runat="server"
RepeatDirection="Vertical"
Border="1"
BorderColor="LightGray"
Font-Size="Large"></asp:RadioButtonList>
</div>
</form>
</body>
</html>
Default.aspx.cs (C# Code)
using System;
using System.Drawing;
using System.IO;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using System.Web.UI.WebControls;
namespace QRCode_Demo
{
public partial class QRCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSelect_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
int i;
for (i = 1; i < 11; i++)
{
CheckBox1.Items.Add(new ListItem(" " + code));
}
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
string code = txtQRCode.Text;
CheckBox1.Visible = false;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = 150,
Height = 150,
Margin = 0,
};
var barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = barcodeWriter.Write(code))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
PlaceHolder1.Controls.Add(imgBarCode);
}
}
}
}

How to insert latitude and longitude in database from click event?

Using ASP.net and WebForms i am trying to store the user's location (Latitude, Longitude) to a database. This presents the problem:
How can i get the user's latitude and longitude into a place where server-side ASP.net code can then save it into a database.
What have you tried?
I don't care which technology is used; i just need their location. My first attempt was to try to use Google Maps in order to access the current location. And while i can use javascript in the browser to get ahold of the current location, i cannot figure out how to transfer that information to the server.
Here's the sample code of my first attempt:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var long = 0;
var lat = 0;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
long = e.latLng.lng();
lat = e.latLng.lat();
alert("Latitude: " + lat + "\r\nLongitude: " + long);
});
}
</script>
<div id="dvMap" style="width: 300px; height: 300px">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</body>
</html>
And below is the .aspx code-behind file. We save the longitude and latitude to the database during the Click event of the button:
protected void Button1_Click(object sender, EventArgs e)
{
//TODO: Ask Stackoverflow how to get these values from browser-land javascript
Double latitude = 0;
Double longitude = 0;
SqlConnection con = new SqlConnection();
con.ConnectionString = "#Data Source=(LocalDB)\v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
string query1 = "insert into Courses(longi,lati) values (#lati, #longi)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#lati", latitude);
cmd1.Parameters.AddWithValue("#longi", longitude);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}
Location API
Nothing says i need to be using Google Maps. I know that HTML has a Location API accessible somewhere, somehow. Is there an established way that the browser's Location API can be used to feed the user's location to the server in ASP.net?
Add asp hidden fields, with runat="server" to hold the lat and lng. When you get the lat and lng in your javascript simply populate the hidden fields with those values. Then you can reference the hidden fields values directly in your OnClick handler.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var long = 0;
var lat = 0;
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(18.9300, 72.8200),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
long = e.latLng.lng();
lat = e.latLng.lat();
document.getElementById("lat").value = lat;
document.getElementById("lng").value = long;
alert("Latitude: " + lat + "\r\nLongitude: " + long);
});
}
</script>
<form id="myForm" runat="server">
<div id="dvMap" style="width: 300px; height: 300px">
</div>
<asp:HiddenField ID="lat" runat="server" />
<asp:HiddenField ID="lng" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
//TODO: Ask Stackoverflow how to get these values from browser-land javascript
Double latitude = Convert.ToDouble(lat.Value);
Double longitude = Convert.ToDouble(lng.Value);
SqlConnection con = new SqlConnection();
con.ConnectionString = "#Data Source=(LocalDB)\v11.0;AttachDbFilename=Database.mdf;Integrated Security=True";
string query1 = "insert into Courses(longi,lati) values (#lati, #longi)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#lati", latitude);
cmd1.Parameters.AddWithValue("#longi", longitude);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}

Getting the rewritten value of a contentEditable tag

in my code i want to set a tag with values from a .mdb database (oleDb) and when the user registers as an administrator i add the contentEditable=true attribute to the parts i want him to be able to edit. when he is done he will hit a 'save' button and the code behind will update the new value into the database.
here is the code: (Admin.LogIn(,); also returns true if the user registered as an admin)
<%# Page Title="" Language="C#" MasterPageFile="~/BenOptic.master" AutoEventWireup="true" CodeFile="ben_info.aspx.cs" Inherits="ben_info" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h1 align="center" id="ben_info_header" runat="server">
</h1>
<h3 align="center" id="ben_info_subheader" runat="server">
</h3>
<p id="ben_info_main_text" runat="server">
</p>
<form id="Form1" action='' method='post' runat='server'><asp:Button id='SaveChanges' Text='שמור' OnClick='saveChanges_Click' runat='server' /></form>
</asp:Content>
and the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class ben_info : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SaveChanges.Visible = false;
DAL data = new DAL();
if (Request.Form["submit"] != null)
{
if (Admin.LogIn(Request.Form["adm_username"], Request.Form["adm_pass"]))
{
ben_info_header.Attributes.Add("contenteditable", Session["isAdmin"].ToString());
ben_info_main_text.Attributes.Add("contenteditable", Session["isAdmin"].ToString());
ben_info_subheader.Attributes.Add("contenteditable", Session["isAdmin"].ToString());
SaveChanges.Visible = true;
SaveChanges.OnClientClick += new EventHandler(saveChanges_Click);
}
}
DataTable config = data.Select("Select * from Config where setting like 'ben_info%'");
foreach (DataRow setting in config.Rows)
{
switch (setting["setting"].ToString())
{
case "ben_info_header": ben_info_header.InnerText = setting["val"].ToString(); break;
case "ben_info_subheader": ben_info_subheader.InnerText = setting["val"].ToString(); break;
case "ben_info_main_text": ben_info_main_text.InnerText = setting["val"].ToString(); break;
}
}
}
public void saveChanges_Click(object sender, EventArgs e)
{
DAL data = new DAL();
data.Execute("update Config set val = '" + ben_info_header.InnerText + "' where setting = 'ben_info_header'");
data.Execute("update Config set val = '" + ben_info_subheader.InnerText + "' where setting = 'ben_info_subheader'");
data.Execute("update Config set val = '" + ben_info_main_text.InnerText + "' where setting = 'ben_info_main_text'");
SaveChanges.Visible = false;
}
}

500 internal server error on hidden __viewstate of asp.net page

I am trying to post the data to cross domain. It works fine if the form is not using runat="server" and its giving 500 internal error while posting when the form is using runat="server".
Upon debugging, I identified that the problem is with auto generated __viewstate code on the page. Please find the below code.
Clientside HTML implementation:
<%# Page Language="C#" CodeFile="Sample.aspx.cs" Inherits="Sample" %>
<!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>
<meta charset="utf-8">
<title>Untitled Page</title>
<link href="FileUpload.css" rel="stylesheet" type="text/css" />
<script id="template-upload" type="text/x-tmpl">
</script>
<script id="template-download" type="text/x-tmpl">
</script>
<script src="../../test/FileUpload/jQueryv1.6.2.js"></script>
<script src="fileupload-js/jquery.ui.widget.js"></script>
<script src="fileupload-js/tmpl.min.js"></script>
<script src="fileupload-js/jquery.fileupload.js"></script>
<script src="fileupload-js/jquery.fileupload-ui.js"></script>
<script src="fileupload-js/locale.js"></script>
<script src="fileupload-js/main.js"></script>
</head>
<body>
<form id="fileupload" method="POST" runat="server">
<CCAB.Web:FileUpload runat="server"/>
</form>
</body>
</html>
Serverside code:
public partial class SaveFile : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
Response.AddHeader("Access-Control-Allow-Origin", "*")
if (Request.HttpMethod == "GET" || Request.HttpMethod == "HEAD")
{
Response.Write("GET Success");
}
else
{
for (int i = 0; i < Request.Files.Count; i++)
{
string filename = Request.Files[i].FileName;
Request.Files[i].SaveAs(#"\\dev2\\share$\\Anna\\test\\" + filename);
Response.Write(filename);
Response.Write("Success");
}
}
}
}
Could you please help me in how to ignore the hidden viewstate code from client side or ignore the response viewstate in server side.
Many Thanks
Anna
Try disabling view state by adding a line of code to your unload handler:
Page.EnableViewState = false;
see this MSDN page
I have found the solution for this problem. Please find below
public class BasePage : Page
{
private static string[] aspNetFormElements = new string[]
{
"__EVENTTARGET",
"__EVENTARGUMENT",
"__VIEWSTATE",
"__EVENTVALIDATION",
"__VIEWSTATEENCRYPTED",
};
protected override void Render(HtmlTextWriter writer)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
int formStart = html.IndexOf("<form");
int endForm = -1;
if (formStart >= 0)
endForm = html.IndexOf(">", formStart);
if (endForm >= 0)
{
StringBuilder viewStateBuilder = new StringBuilder();
foreach (string element in aspNetFormElements)
{
int startPoint = html.IndexOf("<input type=\"hidden\" name=\"" + element + "\"");
if (startPoint >= 0 && startPoint > endForm)
{
int endPoint = html.IndexOf("/>", startPoint);
if (endPoint >= 0)
{
endPoint += 2;
string viewStateInput = html.Substring(startPoint, endPoint - startPoint);
html = html.Remove(startPoint, endPoint - startPoint);
viewStateBuilder.Append(viewStateInput).Append("\r\n");
}
}
}
if (viewStateBuilder.Length > 0)
{
viewStateBuilder.Insert(0, "\r\n");
html = html.Insert(endForm + 1, viewStateBuilder.ToString());
}
}
writer.Write(html);
}
}
Please find more info on this page : http://blogs.msdn.com/b/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx
Many Thanks
Anna

Categories