I've made a simple ASP.net website and everything works fine on my computer. But on my colleague's computer no postbacks are fired although he uses the same OS (Win 7) AND the same browser as I do (IE9).
I don't have any access to his computer right now which makes it kind of hard to debug. Does anybody know what could prevent postbacks on one computer although they work on a different one with the same browser?
(I also tried it on a 3rd computer with different browser and OS and it worked there too)
//update: some code
The following code is one of the pages where the problem occures.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NewList.aspx.cs" Inherits="QAList.NewList" %>
<!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>Items</title>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
<link href="qalist.css" rel="stylesheet" type="text/css" />
<script src="lib/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<style type="text/css">
input[disabled]
{
background-color:#888888;
}
.Filled
{
width: 98%;
}
.Property
{ margin-bottom: 0px;
}
.Date
{
/* this class is only used to indicate that the value is a DateTime value */
}
.PropertyTable td
{
border-bottom: 1px solid #D8D8D8;
padding:1px;
background-color:#F6F6F6;
}
.Suppler_style
{
color: #0000BB;
}
</style>
<script type="text/javascript">
$(function () {
$(".Date").datepicker({ dateFormat: "yy/mm/dd" });
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table style="width: 80%;" border="0" class="PropertyTable" cellspacing="0" cellpadding="0">
<tr>
<td style="width: 227px;">
Project Number</td>
<td>
<asp:TextBox ID="ProjectNumber" runat="server" CssClass="Property" Width="200px"></asp:TextBox>
<asp:Button ID="btApplyPnr" runat="server" Text=" apply "
onclick="btApplyPnr_Click" />
</td>
</tr>
<tr>
<td>
Contract No.</td>
<td>
<asp:DropDownList ID="ddContractNo" runat="server" AutoPostBack="True"
onselectedindexchanged="ContractNo_SelectedIndexChanged"
CssClass="Filled">
</asp:DropDownList>
<input type="hidden" class="Property" id="V_QA_PO_tp_listId" runat="server" />
<input type="hidden" class="Property" id="V_QA_PO_tp_ID" runat="server" />
<input type="hidden" class="Property" id="ContractNo" runat="server" />
</td>
</tr>
<tr>
<td>
ITP No</td>
<td>
<asp:TextBox ID="ITPNo" runat="server" CssClass="Filled Property"></asp:TextBox>
</td>
</tr>
<tr>
<td class="Suppler_style">
ITP Name</td>
<td>
<asp:TextBox ID="ITPName" runat="server" CssClass="Filled Property"></asp:TextBox>
</td>
</tr>
<tr>
<td class="Suppler_style">
Status Delivery/Finish Date</td>
<td>
<asp:TextBox ID="StatusDeliveryFinishDate" runat="server"
CssClass="Filled Property Date"></asp:TextBox>
</td>
</tr>
</table>
</form>
</body>
</html>
And 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;
namespace QAList
{
public partial class NewList : System.Web.UI.Page
{
private string current_contract = "0";
private string current_pnr;
protected void Page_Load(object sender, EventArgs e)
{
current_contract = ddContractNo.SelectedValue;
}
protected void Page_PreRender(object sender, EventArgs e)
{
//load Contract Numbers
ddContractNo.Items.Clear();
ddContractNo.Items.Add(new ListItem("-", "0"));
foreach (DataRow contract in DBAccess.Instance.getContractNumbers(current_pnr).Rows)
{
ddContractNo.Items.Add(new ListItem(contract["ProjectNumber"] + " - " + contract["ContractNo"] + " - " + contract["GoodsServicesSupplied"], contract["tp_listId"] + "_" + contract["tp_ID"]));
}
try
{
ddContractNo.SelectedValue = current_contract;
}
catch (ArgumentOutOfRangeException)
{
ddContractNo.SelectedValue = null;
applyNewContractValue();
}
}
protected void ContractNo_SelectedIndexChanged(object sender, EventArgs e)
{
applyNewContractValue();
}
private void applyNewContractValue()
{
current_contract = ddContractNo.SelectedValue;
if (!String.IsNullOrEmpty(current_contract) && current_contract != "0")
{
Guid tp_listId = new Guid(current_contract.Split('_')[0]);
int tp_ID = Convert.ToInt32(current_contract.Split('_')[1]);
DataRow row = DBAccess.Instance.getContractInfos(tp_listId, tp_ID);
if (row == null)
return;
ITPName.Text = row.IsNull("GoodsServicesSupplied") ? "" : row["GoodsServicesSupplied"].ToString();
if (!row.IsNull("PlannedDeliveryexworks"))
{
DateTime tmp = (DateTime)row["PlannedDeliveryexworks"];
StatusDeliveryFinishDate.Text = tmp.Year + "/" + fillZeros(tmp.Month, 2) + "/" + fillZeros(tmp.Day, 2);
}
}
else
{
ITPName.Text = "";
}
}
private string fillZeros(int nr, int min_length)
{
string res = nr.ToString();
while (res.Length < min_length)
res = "0" + res;
return res;
}
protected void btApplyPnr_Click(object sender, EventArgs e)
{
current_pnr = ProjectNumber.Text;
}
}
}
Check if your collegue got some script blocker installed, those can prevent postbacks since they are Javascript driven.
In case this helps someone:
I had something similar occur and it turned out that it was due to some validation controls on the page. They were for some hidden text boxes that were not actually visible and had no validation group specified. On one of the computers the errors were ignored and the postback worked, whereas on the second computer the postback failed due to validation errors. Because the text boxes were not currently visible, the problem was not immediately obvious.
Once I set up validation groups, the problem went away. I don't know why the behaviour was different on the two computers as both are running Chrome on Windows 10.
Related
my question was that when I send the request to the web server, of course, the web server will take the request and give me a page that will be in the HTML format so I want to know when the web server will execute asp server-side controls into HTML format than in the Testing. aspx.cs file will be changed as well? it means these two lines int no1 = Convert.ToInt32(textbox1.Text);
int no2 = Convert.ToInt32(textbox2.Text);
these two lines will be converted into like this int no1=Convert.ToInt32(Response["textbox1"]);
int no1=Convert.ToInt32(Response["textbox2"]); these two lines will be converted like this or not
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Testing.aspx.cs" Inherits="login.Testing" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="background-image:url(C:\Users\Sudarshan\source\repos\login\login\Images\uWjEogFLUTBc8mSvagdiuP.jpg)">
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
Enter the Number 1:<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Enter the Number 2:<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<center>
<br />
<br />
<asp:Button ID="button1" runat ="server" Text="Add" Height="38px" OnClick="Unnamed1_Click" Width="101px" /> </center>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
--------------------------------------------------------------
Testing.aspx.cs
using System;
using System.Collections.Generic;
using System. Linq;
using System. Web;
using System.Web.UI;
using System.Web. UI.WebControls;
namespace login
{
public partial class Testing: System.Web. UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
int no1 = Convert.ToInt32(textbox1.Text);
int no2 = Convert.ToInt32(textbox2.Text);
int result;
result = no1 + no2;
Response.Write(result);
}
}
}
My ASP.Net app handles authorization with roles just fine, but when someone reaches an unauthorized page, he is kicked back to the login page without any sort of warning.
Is there a way of passing a message to the default login page? Alternatively, is there a way to have an authorization failure redirect to a page that's not the default login page (while maintaining the default page when authorization is needed for the first time)?
I think some of you are misunderstanding what I have.
Here is my login.aspx:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Security" %>
<script runat="server">
void Logon_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(Username.Text, Password.Text))
{
FormsAuthentication.RedirectFromLoginPage(Username.Text, false);
}
else
{
Msg.Text = "Your user name or password is incorrect";
}
}
</script>
<html>
<head id="Head1" runat="server">
<title>Login Screen</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center;">
<h3>You must be logged in to use this application</h3>
<table>
<tr>
<td>
User Name:</td>
<td>
<asp:TextBox ID="Username" runat="server" /></td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="Username"
Display="Dynamic"
ErrorMessage="User Name needs to be filled in"
runat="server" />
</td>
</tr>
<tr>
<td>
Password:</td>
<td>
<asp:TextBox ID="Password" TextMode="Password"
runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2"
ControlToValidate="Password"
ErrorMessage="Password needs to be filled in"
runat="server" />
</td>
</tr>
</table>
<asp:Button ID="Submit1" OnClick="Logon_Click" Text="Log On"
runat="server" />
<p>
<asp:Label ID="Msg" ForeColor="red" runat="server" />
</p>
</div>
</form>
</body>
</html>
and here is the "admin" controller page:
namespace MyApp.Controllers
{
public class AdminController : Controller
{
[Authorize(Roles="SuperUser")]
public ActionResult Index()
{
return View();
}
}
}
If the person who logged in is in the system but does not have the SuperUser role, it returns to the login screen - what I want to do is, I want the user to differentiate between the login screen showing up because the user hasn't logged in yet and the screen showing up because the user did not have the correct role.
Actually, what I want to do for an unauthorized user is to display a separate screen that displays a message and then lets the user return to the app's home screen.
Create a class derived from AuthorizeAttribute and override the method: HandleUnauthorizedRequest
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace MvcAttributes.Infrastructure.customAttributes
{
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
// redirect to your Error page
context.Result =new RedirectResult("/UnauthorizedRequest.html");
// if you want to redirect to some action, use:
// new RedirectResult("/UnAuthorizedUsers/ErrorDetails");
}
}
}
and apply MyAuthorizeAttribute as shown below:
[MyAuthorizeAttribute]
public class ProductController :Controller
{
You can use the ContentResult to return a plain string:
In MVC, how do I return a string result?
if bAuthorized
{
return Content("Unauthorized.");
}
assuming your function looks like this:
function isAuthorized() {
$.ajax({
url: '/Home/isAuthorized',
type: "POST",
data: "some data",
success: function (ret) {
$("#displayresult").html(ret);
},
error: function (ret) {
$("#cdisplayresult").text("Something went wrong!");
}
});
}
I am new to ASP.NET (and web development in general).
For some reason, in my ASP.NET master page, the hyperlink web controls are not working.
I want them as web controls so I can change the "Login" hyperlink text to "Log out" (as well as its navigateURL) if the user session is currently logged in.
Could anyone find the problem?
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="~/Styles/default.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
<style type="text/css">
.style1
{
width: 468px;
}
</style>
</head>
<body>
<form id="Form1" runat="server">
<div id="wrapper" runat="server">
<div id="header" class="container" runat="server">
<table style="width: 100%; height: 128px;" runat="server">
<tr>
<td class="style1" runat="server">
WEBLINK
</td>
<td>
<asp:HyperLink ID="HyperLink1" runat="server">About</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink2" runat="server"
NavigateUrl="~/InterestPages/InterestNews.aspx">Interests</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="HyperLink3" runat="server">Blogs</asp:HyperLink>
</td>
<td>
<asp:HyperLink ID="loginLink" runat="server" NavigateUrl="~/Account/Login.aspx"
ViewStateMode="Enabled">Login</asp:HyperLink>
</td>
</tr>
</table>
</div>
</div>
<asp:ContentPlaceHolder ID="MainContent" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>
Here is my C# master page code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SiteMaster : System.Web.UI.MasterPage
{
private void Page_PreInit(object sender, EventArgs e)
{
if (Session["LoggedIn"] != null && (bool)Session["LoggedIn"] == true)
{
MasterPageFile = "~/LoggedIn.master";
}
else
{
MasterPageFile = "~/Site.master";
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["LoggedIn"] != null && (bool)Session["LoggedIn"] == true)
{
loginLink.Text = "Log out";
loginLink.NavigateUrl = "";
}
else
{
loginLink.Enabled = true;
loginLink.Text = "Login";
loginLink.NavigateUrl = "~/Account/Login.aspx";
}
}
}
Why not just replace your login menu link with the asp LoginView control?
You can add an Anonymous template with your login link to point to your login page, and
a LoggedIn template with your logout link by adding the LoginStatus.
It let's you provide a welcome to the logged user.
Oh, and it also let's you get rid of all that preinit stuff and session tracking.
You can use the user identity isAuthenticated to determine if that session is logged in.
And if you want to use a different master page for your login page ... you can just create one for your login page or point it to another master page.
I also don't think your pre-init is firing.
You have empty NavigateUrl when session is not null . So please change this line loginLink.NavigateUrl = "#";
try this code
if (Session["LoggedIn"] != null && (bool)Session["LoggedIn"] == true)
{
loginLink.Text = "Log out";
loginLink.NavigateUrl = "#";
}
else
{
loginLink.Enabled = true;
loginLink.Text = "Login";
loginLink.NavigateUrl = "~/Account/Login.aspx";
}
We're 4 guys making a website for our final school project. We need to allow a user to upload a pdf. We're using Visual Studio 2012, and we have a Master page set up, and the whole login-process and user-creation works. We're using jQuery, and also jQueryMobile because the site needs to work for phones as well, and this makes it a bit easier.
But when we want to check the files the client is trying to upload in our code behind, Request.Files is always empty. Why is this?
I have the enctype set in the form I'm using, so I should be fine. It looks like the page reloads when I click the upload-button, and the text-field in the file-input gets cleared. Then after this, it runs the code behind method.
The output we get is:
HALLOOOOOOOOOOOOOO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
In the house
Files[] size is 0
The Master page that looks like this:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Main.Master.cs" Inherits="SendEtBrev.Main" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SendEtBrev.dk</title>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;" />
<meta name="MobileOptimized" content="width" />
<meta name="HandheldFriendly" content="true" />
<link rel="stylesheet" type="text/css" href="/Styles/reset.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="/Js/fixes.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<link rel="stylesheet" type="text/css" href="/Styles/sendetbrev.css" />
<asp:ContentPlaceHolder ID="head" runat="server" />
</head>
<body>
<header>
<div class="headerbox">
<div class="headerlogo">
<img class="autosizedimage" src="/Billeder/Logo.png" />
</div>
<asp:LoginView ID="LoginViewMenu" runat="server">
<LoggedInTemplate>
Min konto
Log ud
</LoggedInTemplate>
</asp:LoginView>
<br />
</div>
</header>
<br />
<br />
<div>
<asp:ContentPlaceHolder ID="centercontent" runat="server" />
</div>
<footer>
</footer>
</body>
</html>
My ASPX code is this:
<%# Page Language="C#" MasterPageFile="~/Main.Master" ValidateRequest = "False" AutoEventWireup="true" CodeBehind="Side1Uploadfil.aspx.cs" Inherits="SendEtBrev.SendBrev.Side1Uploadfil" %>
<asp:Content ID="Content1" ContentPlaceHolderID="centercontent" runat="server" >
<asp:Literal ID="introText" runat="server"/>
<br />
<br />
<asp:Literal ID="AccepteredeFormater" runat="server" />
<br />
.pdf<br />
<!-- vises kun hvis der er en fejlbesked ved upload -->
<asp:Literal ID="errorMessage" runat="server" EnableViewState="false" /><br />
Select a file to upload:
<form id="form1" name="form1" method="post" runat="server" enctype="multipart/form-data" >
<input type="file" accept="*.pdf" id="fileUploadControl" name="fileUploadControl" runat="server" />
<asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
<br/><br/>
<br />
</form>
<asp:Button ID="FortsaetKnap" runat="server" data-role="none" CssClass="knap1" Visible="False"
OnClientClick="javascript:location.replace('/SendBrev/Side2Modtager.aspx');" /><br />
</asp:Content>
And my code behind is this:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.IO;
namespace SendEtBrev.SendBrev
{
public partial class Side1Uploadfil : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
introText.Text = "Du er nu klar til at sende et brev.";
AccepteredeFormater.Text = "Følgende filformater accepteres:";
FortsaetKnap.Text = "Fortsæt";
btnUpload.Text = "Upload";
}
protected void btnUploadClick(object sender, EventArgs e)
{
Response.Write("HALLOOOOOOOOOOOOOO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Console.WriteLine("HALLOOOOOOOOOOOOOO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
Debug.WriteLine("HALLOOOOOOOOOOOOOO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if (fileUploadControl != null)
{
Response.Write("In the house");
Console.WriteLine("In the house");
Debug.WriteLine("In the house");
}
if (Page.Request.Files.Count > 0)
{
{
//Get the first file. There could be multiple if muti upload is supported
string fileName = Page.Request.Files[0].FileName;
//Some validation
if (Page.Request.Files[0].ContentLength > 1 && !string.IsNullOrEmpty(fileName))
{
FileValidator(Page.Request.Files[0].InputStream);
}
}
}
else
{
Debug.WriteLine("Files[] size is 0");
Console.WriteLine("Files[] size is 0");
Response.Write("Files[] size is 0");
}
}
protected void FileValidator(Stream myFileStream)
{
Debug.WriteLine("Running FileValidator...");
Console.WriteLine("Running FileValidator...");
Response.Write("Running FileValidator...");
if (myFileStream != null)
{
using (StreamReader sr = new StreamReader(myFileStream))
{
Regex regex = new Regex(#"/Type\s*/Page[^s]");
MatchCollection matches = regex.Matches(sr.ReadToEnd());
Console.Write("PDF'en har " + matches.Count + " sider");
Debug.Write("PDF'en har " + matches.Count + " sider");
Response.Write("PDF'en har " + matches.Count + " sider");
if (matches.Count > 0)
{
FortsaetKnap.Visible = true;
}
}
}
else
{
Debug.WriteLine("Filestream is null");
Console.WriteLine("Filesream is null");
Response.Write("Filestream is null");
FortsaetKnap.Visible = false;
}
}
}
}
It happens because ajax is used by default in jQueryMobile. And on that case file upload does not work.
So Adding data-ajax="false" to form should fix it.
<form id="form1" name="form1" data-ajax="false" method="post" runat="server"
enctype="multipart/form-data" >
In case you are using Razor
Some useful links:
File upload support on mobile
XMLHttpRequest 2 -Browser support
jQuery File Upload - Browser support
I always got this error:Compiler Error Message: CS0103: The name 'txtUserName' does not exist in the current context
mypage.aspx
<% #Page Language="C#" Inherits="myclass" Src="myclass.cs" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Username:
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="Writedata" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
myclass.cs
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Text;
public class myclass:Page
{
protected void WriteData(object sender, EventArgs e){
string customer_id=txtUserName.Text;
string postData="customer_id="+customer_id;
byte[] data= Encoding.UTF8.GetBytes (postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://myserverurl.com/mypage.php");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
}
}
Any help here?
Thanks,
Try changing your class declaration to "public partial class myclass:System.Web.UI.Page". The partial keyword is, I believe, critical for the compiler to know the balance of the class definition is created in temp/intermediate files it won't know about otherwise.