Good day,
Been new to web development (i use ASP.NET) and i had this goal of passing/returning a value to display on HTML element such such as input. I had done searching and trying most of the solutions i found but none work, the output still returns an empty value on the HTML input. why is that? my code i'm working on can be seen below:
javacript:
function confirmExistence(entityValue) {
var entity = "Staff";
var result = "";
if (entityValue === '0') {
entity = "Student";
}
if (confirm(entity + " w/ same name is already registered. is this a different " + entity + "?")) {
result = "Yes";
} else {
result = "No";
}
alert(result);
document.getElementById('<%= fieldFirstNameStudent.ClientID %>').value = result;
}
html:
<asp:button class="by-button" id="btnStudentEnc" runat="server" text="Encode" OnClick="btnStudentEnc_Click" />
<asp:textbox type="text" class="mfield" placeholder="First Name" id="fieldFirstNameStudent" runat="server" />
asp c#:
protected void btnStudentEnc_Click(object sender, EventArgs e)
{ **some sql database condition here to run the clientscript below**
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true); }
Result is as follows on this image:
UPDATE: IF ABOVE IS TOO COMPLICATED. i created a new web form having simple block of codes that still doesn't work
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="LobbyStudents.aspx.cs" Inherits="LobbyStudents" %>
<asp:Content ID="Content0" ContentPlaceHolderID="title" Runat="Server">
LobbyStudents
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:textbox placeholder="First Name" id="fieldFirstNameStudent" runat="server"/>
<asp:button runat="server" text="Encode" OnClick="btnStudentEnc_Click"></asp:button>
</asp:Content>
Aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class LobbyStudents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStudentEnc_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true);
}
}
ClientScript works and even does the alert box. Still textbox is still empty and doesn't contain "whatswrong?" value
unlike i try it on this one:
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="tch">
<p>Click the button to change the value of the text field.</p>
<button onclick="confirmExistence('0')">Try it</button>
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("myText").value = "whatswrong?";
}
</script>
</body>
</html>
where it works.
What's the difference between the two and why it doesn't happen on asp controls
ok, figure out what is the issue for your first example, is not related to the position, but
change your
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
to
document.getElementById("<%= fieldFirstNameStudent.ClientID %>").value = "whatswrong?";
this will generated in html as
document.getElementById("System.Web.UI.WebControls.TextBox").value = "whatswrong?";
which the js not able to find the control name as System.Web.UI.WebControls.TextBox
if assign with .ClientID, it will generate the correct id
document.getElementById("MainContent_fieldFirstNameStudent").value = "whatswrong?";
Related
I am using ASP.NET UpdatePanel for partial postback. Somehow after the server side postback (ddl_SelectedIndexChanged), the value set by a Javascript function (lblTotal's value of 100) gets removed. Is there anyway to preserve value set by the Javascript function?
JavaScript:
<script type="text/javascript">
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
lblTotal.innerHTML = "100";
}
</script>
HTML:
<asp:UpdatePanel ID="UpdateGrid" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddl" runat="server" OnTextChanged="ddl_SelectedIndexChanged" AutoPostBack="true" />
<asp:CheckBox ID="chkLevels" runat="server" onclick="calculateTotal()" />
<asp:Label ID="lblTotal" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
C# / Code Behind:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
// Some code
}
The problem is here is that when you change data with calculateTotal in Javascript, server does not know about changes since you don't post back data to server.
So you need to trigger the postback event with __doPostBack():
Client side:
function calculateTotal() {
var lblTotal = document.getElementById("<%= lblTotal.ClientID%>");
//Calculation
var totalValue = "100";
__doPostBack('chkLevels', totalValue);
}
Page_Load on Server side :
protected void Page_Load(object sender, EventArgs e)
{
if (Request["__EVENTTARGET"] == "chkLevels")
{
var totalValue = Request["__EVENTARGUMENT"];
lblTotal.Text = totalValue;
}
}
See: how to use __doPostBack function in asp.net
I've been struggling for a while with a Javascript/C# issue i have. I've been trying to set a Session variable from Javascript. I tried to use page methods before but it resulted in my javascript crashing.
In the javascript :
PageMethods.SetSession(id_Txt, onSuccess);
And this page method :
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
Page aPage = new Page();
aPage.Session["id"] = value;
return value;
}
I haven't had any success with this. Therefore, i tried to set the value of a textbox from my javascript and put a OnTextChanged event in my c# to set the session variable but the event is not fired.
In the javascript:
document.getElementById('spanID').value = id_Txt;
In the html :
<asp:TextBox type="text" id="spanID" AutoPostBack="true" runat="server"
ClientIDMode="Static" OnTextChanged="spanID_TextChanged"
style="visibility:hidden;"></asp:TextBox>
In the cs :
protected void spanID_TextChanged(object sender, EventArgs e)
{
int projectID = Int32.Parse(dropdownProjects.SelectedValue);
Session["id"] = projetID;
}
Does anyone have an idea as of why none of my events where fired ? Do you have an alternative solution that I could try ?
I found the issue, I didn't have the enableSession = true and i had to use the HttpContext.Current.Session["id"] = value, like stated by mshsayem. Now my event is fired properly and the session variable is set.
First, ensure you have sessionState enabled (web.config):
<sessionState mode="InProc" timeout="10"/>
Second, ensure you have page-methods enabled:
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Third, set session value like this (as the method is a static one):
HttpContext.Current.Session["my_sessionValue"] = value;
Sample aspx:
<head>
<script type="text/javascript">
function setSessionValue() {
PageMethods.SetSession("boss");
}
</script>
</head>
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<asp:Button ID="btnSetSession" Text="Set Session Value (js)" runat="server" OnClientClick="setSessionValue();" />
<asp:Button ID="btnGetSession" Text="Get Session Value" runat="server" OnClick="ShowSessionValue" />
<br/>
<asp:Label ID="lblSessionText" runat="server" />
Sample code behind:
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
HttpContext.Current.Session["my_sessionValue"] = value;
return value;
}
protected void ShowSessionValue(object sender, EventArgs e)
{
lblSessionText.Text = Session["my_sessionValue"] as string;
}
I am working on a group project, and am trying to figure out ASP.net (hardly anyone in my group knows it, including me). My job is to make some text box and button such that, when the button is clicked, the text in the text box is processed and posted iff it has <= 140 characters.
I tried to write some jQuery that checks the text in the text box, and then sends it to the server for processing. The server is to save it to database, and post it to page, if it is no more than 140 characters long (this will be checked again).
Unfortunately, I run into this error. I tried to contact my team members, but they are super busy with other issues. Here is my code:
Feed.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Feed.aspx.cs" Inherits="Feed_Feed" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<!-- This is here for test purpose -->
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(
function()
{
$('#TweetButton').click(
function()
{
// get the text from the TweetBox
var status = $('#TweetBox').val();
// if it is 140 characters or less
if (status.length <= 140)
{
var data = JSON.stringify(status);
// send to the server page
$.ajax({
url: '/Feed.aspx.cs',
type: 'POST',
dataType: 'json',
data: data,
success: function(myStatus)
{
$('#MyStatus').html(myStatus);
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<h1>User Feed</h1>
<p>
<input id="TweetBox" type="text" /><input id="TweetButton" type="button" value="button" />
</p>
<div id="MyStatus"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="LeftContent" Runat="Server">
</asp:Content>
Feed.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
The C# file is practically empty because I don't know how to handle the data being posted to the page (should it be in Page_Load?) I don't know what to do here...
The code is not going to post data to the asp.net server because you are just using regular HTML elements. In order to convert an html element to asp.net element, you need to use attribute runat="server", so your markup would become :
<input id="TweetBox" type="text" runat="server" /><input id="TweetButton" type="button" value="button" runat="server" />
Alternately, to make the job simpler and have more flexibility on the asp.net controls ( like accessing additional properties ), you should strictly use asp.net core controls. So your new markup would look like :
<asp:TextBox id="TweetBox" runat="server"></asp:TextBox>
<asp:Button id="TweetButton" runat="server"></asp:Button>
In order to trigger a click event to post data onto the server ( codebehind ), you need to add the attributes OnClick to your button.
<asp:Button id="TweetButton" runat="server" OnClick="TweetButton_Click"></asp:Button>
In the codebehind (*.aspx.cs), you need to handle the event triggered by the button and check for the length of the text.
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TweetButton_Click(object sender, EventArgs e)
{
if(TweetBox.Text.Length <= 140)
{
// Save data in the database.
}
}
}
UPDATE :
To work with ajax, you would need asp.net controls, so your markup would be
.ASPX =>
<input id="TweetBox" type="text" />
<input id="TweetButton" type="button" value="button" />
<script>
$().ready(function()
{
$('#TweetButton').click(function(){
// if it is 140 characters or less
if (status.length <= 140)
{
// send to the server page
$.ajax({
url: '/Feed.aspx/SubmitTweet',
type: 'POST',
dataType: 'json',
data: "{'tweet':'" + $('#TweetBox').val() + "'}",
success: function(myStatus)
{
$('#MyStatus').html(myStatus.d);
},
error : function(er)
{
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
.ASPX.CS ( code-behind ) =>
[WebMethod]
public static string SubmitTweet(string tweet)
{
// dummy function :
return DataSubmit(tweet) ? "Data Was submitted" : "Error while submitting data";
}
public bool DataSubmit(string data)
{
//call db connection and save the tweet
// if successful , return true else false
}
I want my web application to print w popup page just after appearance automatically without asking the client to choose with printer to be choose.
how can I handle silent printing in ASP.Net with java-script or ajax or what is the most suitable solution for this case?
You can't and for good reasons, such as:
The user should always be able to choose which printer they want to use.
The user should always be able to choose whether they print something or not (imagine the spam that would constantly fly out of your printer otherwise)
Some third party controls are available for this(in WPF). Please check whether this is useful in asp.net also.
http://www.textcontrol.com/en_US/support/documentation/dotnet/n_wpf_printing.printing.htm
//OnTouchPrint.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.Drawing.Printing;
using System.IO;
using System.Drawing;
namespace TokenPrint
{
public partial class Try : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
SolidBrush Brush = new SolidBrush(Color.Black);
string printText = TextBox1.Text;
g.DrawString(printText, new Font("arial", 12), Brush, 10, 10);
}
protected void Press_Click(object sender, EventArgs e)
{
try
{
string Time = DateTime.Now.ToString("yymmddHHMM");
System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
ps.PrintToFile = true;
// ps.PrintFileName = "D:\\PRINT\\Print_"+Time+".oxps"; /* you can save file here */
System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
System.Drawing.Printing.StandardPrintController printControl = new System.Drawing.Printing.StandardPrintController();
pd.PrintController = printControl;
pd.DefaultPageSettings.Landscape = true;
pd.PrinterSettings = ps;
pd.Print();
TextBox1.Text = "";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Printed Successfully.Check: Drive D')", true);
}
catch (Exception ex)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Try.aspx");
}
}
}
//OnTouchPrint.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OnTouchPrint.aspx.cs" Inherits="TokenPrint.Try" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" Width="235px" Height="142px"
TextMode="MultiLine"></asp:TextBox>
<br />
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Empty message can not be printed!"
ValidationGroup="vgp1"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="Press" runat="server" Text="Press" onclick="Press_Click"
ValidationGroup="vgp1" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Refresh"
ValidationGroup="vgp2" />
</form>
</body>
</html>
i have default.aspx page and one user control.
usercontrol is having following code for multiple file uploads.
now the problem is when i add a file for upload that current context file is not giving me any value it is still zero i guess because it is rendering from user control.
what should i do?
My Usercontrol UPLOAD.ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeFile="FileUpload.ascx.cs" Inherits="FileUpload" %>
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
var i = 1;
$(document).ready(function () {
$("#addfile").click(function () {
$("#dvfiles").append("<input name=" + i + "fu type=file /><a href=#>remove</a><br>");
i++;
});
$("#dvfiles a").live('click', function () {
$(this).prev("input[type=file]").remove();
$(this).remove();
});
});
$(document).submit(function () {
var flag = true;
$("#dvfiles input[type=file]").each(function () {
if ($(this).val() == "") {
$(this).css("background", "Red");
flag = false;
}
});
return flag;
});
</script>
<div id="Fileuploader">
Attach a file..<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
onclick="btnUpload_Click" />
</div>
UPLOAD.ASCX.CS
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
HttpFileCollection filecolln = Request.Files;
//here i don't get values of current files.
// this is zero. because of this following if condition failed
//please help here
if (filecolln.Count > 0)
{
for (int i = 0; i < filecolln.Count; i++)
{
HttpPostedFile file = filecolln[i];
if (file.ContentLength > 0)
{
file.SaveAs(ConfigurationManager.AppSettings["FilePath"] + System.IO.Path.GetFileName(file.FileName));
}
}
lblMessage.Text = "Uploaded Successfully!";
}
else
{
lblMessage.Text = "No files selected!";
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
Default.aspx code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%# Register TagPrefix="ucFileuploader" tagName="Fileuploader" src="FileUpload.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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ucFileuploader:Fileuploader ID="Fileuploder" runat="server" />
</div>
</form>
</body>
</html>
The problem is that you are using javascript an id names.
so when you have control with id addfile in .aspx it is rendered as is,
but when you have control with id addfile in user control with id Fileuploader,
than the rendered id is Fileuploader_addfile,
so change id name in java script with the proper id.
To chechk what is name of rendered id, open page in browser, open source of the page and find you element and copy id into java script.
Change all ids in java script with rendered id names.
I would suspect it could be this line:
<script type="text/javascript" src="_scripts/jquery-1.4.1.min.js"></script>
Which should be:
<script type="text/javascript" src="/_scripts/jquery-1.4.1.min.js"></script>