HTML button sending input text data to ASP side - javascript

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
}

Related

Is there a way to reference a asp ID using a variable in code behind

I am trying to use a c# variable to remove an attribute.
I am testing my approach before actually coding application.
I've tried javascript and jQuery but found nothing that would allow to
substitute TextBox ID with value of string in codebehind.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication2.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="myText" runat="server" required="required"></asp:TextBox>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string straspID = "myText";
bool fieldRequired = false;
if (fieldRequired == false)
{
//FindControl("myText");
FindControl(straspID);
if (straspID != null)
//
myText.Attributes.Remove("required");
// I want to use straspID instead of the ID of the asp page
// which will returned from a table - I'm simulating here
// I get an error if I use straspID for remove attribute
}
}
}
}
My expected result is to remove the attribute for selected ID.
I am currently getting a syntax error.
This
FindControl(straspID);
is not doing what you think it is.
Can you check your index.aspx.designer.cs file and see if there is a protected member variable called 'myText' ?
If there is, you can simply do this: -
if (fieldRequired == false)
{
myText.Attributes.Remove("required");
}
If there is no protected member called myText, add one at class level to 'index': -
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected Textbox myText;
(etc)
As long as you declare it of the correct type and with the same name and casing, there is no need to resort to FindControl to access a server control.
private void loadform(List providerList)
{
foreach (ProviderInRequest req in providerList)
{
// taget div for plan
Control ctrl = FindControl("div" + req.aspName);
// set visible to true if we found it.
if (ctrl != null)
{
//set div to visible
ctrl.Visible = true;
// set label to proper text
Label lbl = (Label)Page.FindControl("lbl" + req.aspName);
lbl.Text = displayName;

how to pass value from javascript to ASP control

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?";

asp.net trigger button click on server side from postback manually

I have an asp.net page. & I am using jquery confirm plug in from here.
https://craftpip.github.io/jquery-confirm/
I want that when user clicks a button, they are prompted for a confirm dialog & when they say confirm,only then my button click on server should get fired. I do not want to use the window.confirm dialog.
I was able to use jquery confirm & called postback manually via Button's ClientClick property.
The __doPostBack event is firing. However, the click event on server side for the button is not getting fired.
What am i missing ?
ASPX Code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Tester.aspx.cs" Inherits="BLF_Gauri.Tester" %>
<html>
<head>
<script src="Scripts/jquery-2.1.0.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.3/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.3/jquery-confirm.min.js"></script>
</head>
<body>
<form runat="server">
<asp:Button ID="Button2" runat="server" Text="YEs" OnClick="Button2_Click"
OnClientClick="return TestClick(this);" />
</form>
<script type="text/javascript">
function TestClick(x)
{
jQuery.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
__doPostBack("'" + x.id + "'", 'OnClick');
},
cancel: function () {
// Do Nothing
}
}
});
return false;
}
</script>
</body>
</html>
The Code Behind : (Simplified)
protected void Page_Load(object sender, EventArgs e)
{
//IT COMES HERE.
}
protected void Button2_Click(object sender, EventArgs e)
{
//IT DOES NOT COME HERE.
}
So I solved this!! Instead of using __dopostback I used this.
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions("" + x.name + "", "", true, "", "", false, true));
x.name coz inside a master page. id changes.

BlockUI during partial postback through JavaScript

I have an ASP.NET page (WebForm1) that opens a modal dialog WebForm2 (via OpenForm2() js function) for some further processing. Upon closing the dialog I just update the UpdatePanel via JavaScript. Now the problem is, during this js call it doesn't block the UI.
This is only happening when I am calling the OpenForm2 js method from the server side (Button1_Click). As the UI already went into block mode, upon closing the WebForm2 it doesn't wait for the completion of partial postback (JavaScript) and unblocks the UI.
If I directly call the OpenForm2 js function in OnClientClick tag of the button (Button 2 in the sample), it works well and keeps blocking the UI till completion of postback.
I tried wrapping the partial postback js code in an add_endRequest, but in that case it keeps calling the refreshUpdatePanel() js method, hence blocking/unblocking the UI keeps going on. May this be happening due to two add_endRequest used on a page in that case?
Any assistance is highly appreciated in this regard.
NOTE: I have used jQuery blockUI for blocking the page during partial postbacks.
The code sample for the WebForm1 page is as follows. (The WebForm2 aspx page just have a button to close the dialog and a related js function).
WebForm1.aspx
<head runat="server">
<title></title>
<script src="js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="js/jquery.blockUI.js" type="text/javascript"></script>
<script type="text/javascript">
function OpenForm2() {
var url = "WebForm2.aspx";
var width = 950;
var height = 455; // screen.availHeight - (120 + 65);
// open modal dialog
obj = window.showModalDialog(url, window, "dialogWidth:" + width + "px; dialogHeight:" + height + "px; center:yes");
// partial postback to reflect the changes made by form2
refreshUpdatePanel();
//Sys.WebForms.PageRequestManager.getInstance().add_endRequest(refreshUpdatePanel);
// ** here it doesn't wait for the completion and unblocks the UI **
}
function refreshUpdatePanel() {
//window.__doPostBack('UpdatePanel1', '1');
// a timeout/delay before a client side updatepanel postback. That compelled the UI to go in blocking again with a little screen flickering.
setTimeout('__doPostBack("<%= UpdatePanel1.ClientID %>", "1")', 0);
}
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
$.blockUI.defaults.css = {};
function InitializeRequest(sender, args) {
// Whatever you want to happen when the async callback starts
$.blockUI();
}
function EndRequest(sender, args) {
// Whatever you want to happen when async callback ends
$.unblockUI();
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
<asp:Label ID="Label2" runat="server" Text=""></asp:Label><br />
<asp:Button ID="Button1" runat="server" Text="Button 1" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button 2" OnClientClick="OpenForm2();return false;" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
WebForm1.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
// some server side processing here
System.Threading.Thread.Sleep(1000);
// then calling javascript function to open form2 as modal
ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "Button1Click", "OpenForm2();", true);
}
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
if (parameter == "1")
{
System.Threading.Thread.Sleep(3000);
Label2.Text = DateTime.Now.ToString();
}
}
use
function refreshUpdatePanel() {
__doPostBack"<%= UpdatePanel1.ClientID %>", '1');
}
instead of
function refreshUpdatePanel() {
window.__doPostBack('UpdatePanel1', '1');
}
thank you

Label id is changing, how to fix this?

I have this asp:label in my page and what I want is to change the text from time to time. But label id is changing from page to page when i run the code. its been appended with "ctl00_bh_" something...
how to fix this?
here are my code snippets.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "onLoad", "DisplaySessionTimeout()", true);
}
<asp:Label ID="lblSessionTime" runat="server" />
function DisplaySessionTimeout() {
document.getElementById("lblSessionTime").innerHTML = "updating text here";
sessionTimeout = sessionTimeout - 1;
if (sessionTimeout >= 0)
window.setTimeout("DisplaySessionTimeout()", 1000);
else
{
alert("Your current Session is over.");
}
}
thanks
In your Javascript you are trying to access the server side control, you need to use the ClientID, try
document.getElementById("<%= lblSessionTime.ClientID%>").innerHTML ="updating text here";
Or ClientIDMode in aspx page if you are using .Net framework 4 or higher
<asp:Label ID="lblSessionTime" runat="server" ClientIDMode="Static" />

Categories

Resources