ASP.NET .aspx page: how to send extra data back via Javascript? - javascript

I have an old-fashioned ASP.NET plain .aspx page.
It has some server-side controls, some buttons to postback, etc.
I'm going to add some Javascript on the client side to create a list of extra data that the user builds.
I don't know beforehand how much of this extra data will be sent. So I can't, for example, just add 10 hidden input fields and check their values in the codebehind.
There might be 20 values sent back, there might be 100.
What's the best way to POST this extra data back to the server?
One way I can imagine it working is to add some dummy hidden list controls, to be filled in by JS on the client. It feels hacky, but I think I could make it work.
Is there a better way?
Some things to note:
I'm not using MVC or AJAX
Not using JQuery (though I could, I suppose)
I'm really just trying to get a handle on my options.
Thanks!

If it doesn't need to be POSTed via ajax you can use javascript to create the controls and then use Request.Form to retrieve the input values.
ASPX:
<script>
document.write('<input name="field1" type="text" />' +
'<input name="field2" type="text" />');
</script>
<asp:Button ID="btn" Text="button" runat="server" onclick="btn_Click" />
ASPX.CS:
protected void btn_Click(object sender, EventArgs e)
{
var keys = Request.Form.AllKeys;
foreach (var key in keys)
{
if (key.StartsWith("field"))
Response.Write(Request.Form[key]);
}
}

Related

execute javascript after download a file (RegisterStartupScript)

I want to execute a RegisterStartupScript calling a Javascript function after certain processes happen in my code behind. It is basically a Loading loop decoration made in CSS3. I show it (with javascript) on buttons clientclick, when I know the process will take a while and I hide it when the process is finished. Everything works fine, but now I have a process in Which I download a file using another empty webform using response.redirect. The file is downloaded fine, but the RegisterStartupScript call does not work. I understand the response is the problem, but nor I need to work in a workaround to solve this (I do not want to change the whole way, cause it is implemented in many other pages and processes. I wil provide the related code (not all), in case you can give me a direct way to solve it.
Javascript
function LoadingLoopOn()
{
$('#outerAlignId').addClass("outerAlign");
$('#middleAlignId').addClass("middleAlign");
$('#innerAlignId').addClass("innerAlign");
$('#OutterCircleId').addClass("OutterCircle");
$('#InnerCircleId').addClass("InnerCircle");
$('#Loadinglbl').addClass("LoadingLabelStyle");
}
function LoadingLoopOff()
{
$('#outerAlignId').removeClass("outerAlign");
$('#middleAlignId').removeClass("middleAlign");
$('#innerAlignId').removeClass("innerAlign");
$('#OutterCircleId').removeClass("OutterCircle");
$('#InnerCircleId').removeClass("InnerCircle");
$('#Loadinglbl').removeClass("LoadingLabelStyle");
}
HTML (it is on the master page, to be able to used it in every webform)
<asp:Panel ID="outerAlignId" ClientIDMode="Static" runat="server" CssClass="outerAlign">
<div id="middleAlignId" class="middleAlign">
<div id="innerAlignId" class="innerAlign">
<div id="OutterCircleId" class="OutterCircle"></div>
<div id="InnerCircleId" class="InnerCircle"></div>
<asp:Label ID="Loadinglbl" ClientIDMode="Static" runat="server" Text="Loading..." CssClass="LoadingLabelStyle"></asp:Label>
</div>
</div>
</asp:Panel>
HTML Button Sample Where I want to used it
<asp:ImageButton ID="ExportExId" ClientIDMode="Static" runat="server" OnClientClick="LoadingLoopOn();" OnClick="ExportExId_Click" CssClass="..." ImageUrl="..." />
And the CS# Code behind
protected void ExportExId_Click(object sender, ImageClickEventArgs e)
{
//...
//Many code and DB treatment goes here, to finally get a temporally Excel file in the server
//..
//I call the page with the file name and path
Response.Redirect(String.Format("DownloadForm.aspx?FileName={0}&Path={1}", fileExported.Name, "Temp" + UserName));
//This piece of code must be excuted in its webform after the redirect (once ee finished)
ScriptManager.RegisterStartupScript(this, GetType(), "LoadingLoopOff", "LoadingLoopOff();", true);
}
As I marked in my comment, A possible solution could be AJAX. Make an ajax call to force a page update and then the function would be processed (on the load), or directly call the function through this ajax call. The problem is that I do not know how to uise AJAX in this case...
Many thanks,

Send Command.Value via Javascript to codebehind

I am fairly new to ASP.Net and I am stuck.
If my Hyperlink is clicked a Command.Value should be sent to the server. After getting that Command.Value the code behind should check if it is right and redirect to a specific site otherwise just reload the page.
Here is my Hyperlink:
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.FormServer.Command.value =
'test';document.FormServer.submit();"
>Test!!</asp:HyperLink>
First of all I want to ask if my Hyperlink is right. Furthermore I am a bit stuck on the code behind regarding where I need to insert my If statement.
I believe it's much easier to send a parameter by GET in the url of your link. But if for any reason you want to do it by post and using javascript then try this.
Web form: param1 is a hidden field which value will be set using Javascript. When the form is submitted the hidden field is posted with the form.
<form id="FormServer" runat="server" >
<input type="text" id="param1" name="param1" style="display:none;" />
<div>
<asp:HyperLink
ID="Link"
runat="server"
Visible="true"
NavigateUrl="javascript:document.getElementById('param1').value = 'test';document.forms['FormServer'].submit();"
>Test!!</asp:HyperLink>
</div>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
string param1Value = Request["param1"];
if (param1Value == "test")
Response.Redirect("~/Default.aspx");
else if(param1Value == "lost")
Response.Redirect("http://www.google.com");
}
In the code behind it might be useful to check this.IsPostBack. That tells you why the page is being loaded. If it's because the link was clicked then IsPostBack will be true.

Struts2: Autopopulating fields based on a dropdown value without JavaScript

I tried searching the site but could not find an answer to my question.
i am developing a java Struts2 web application.
There are 3 form fields on a jsp page as follows:
(Struts2 tags are being used)
<s:form action="action1">
other fields
......
<s:select name="test1" list="{'A','B','C'}"></s:select>
<s:textfield name="test2"></s:textfield>
<s:textfield name="test3"></s:textfield>
.....
other fields
<s:submit value="submit1"><s/submit>
</s:form>
when a value is selected in test1 field, test2 and test3
would needed to be populated from the database based on the
value selected in test1.
as per the process i need to implement, i need to do some calculations based on the input from jsp1(presented above), and present the result on jsp2 which has to have entirely different content from jsp1. My issue is limited to the data entry in jsp1.
what would be the best way of doing this without javascript?
assume that javascript is disabled in the browsers accessing
the application.
thanks,
EDIT
It seems that there's a bit of confusion here, let's try to make it clear:
There are basically three ways of triggering a communication with the server from the browser:
submit HTML
submit JS
AJAX submit
You may or may not care about giving support to users browsing with JavaScript disabled;
if you DO NOT care, then you can proceed as you wish;
if you DO care, then you have two ways in front of you:
make an unique version of the pages, that works both with and without JS (by using ONLY option "1", "submit HTML");
make the pages working in two possible ways, mutually exclusive: while processing the page, you detect if the user has javascript enabled: if yes, you go with JS (submit or AJAX), if not, you fallback to the non JS solution ( "submit HTML" ).
Both this two solutions works with and without JS, but the latter is generally preferred because you can set up a nice, good-looking, user's experience-oriented WebApp for the 99% of the users, by using JavaScript and eventually AJAX, and create a fallback solution for the 1% of the users that, even if the site won't be nice as in the JS version, and even if it won't have ALL the features of the JS version, it would still be usable, and the core functionalities will be available.
As I said in the comment above, there is no need for the fallback version of the WebApp to be as nice, as fast, as good in user experience as the JS version: it should simply... work.
For example, this JSP will work in both cases: it will do a JavaScript Submit after selecting an element from the Select if JS is enabled, and it will do a submit after pressing the Submit button if JS is disabled.
With JS disabled, onchange will be ignored and <noscript> processed.
With JS enabled, onchange will be processed and <noscript> ignored.
<s:form action="myAction">
<s:select onchange="javascript:document.forms[0].submit();"
name="test1" value="test1" list="{'A','B','C'}" />
<s:textfield name="test2" value="test2" />
<noscript>
<span>
Since you have JS disabled,
you need to manually press to the GO button,
but you still can make it work ;)
</span>
<s:submit value="go" />
</noscript>
</s:form>
in your Action
public class MyAction extends ActionSupport{
private String test1="";
private String test2;
/* Getters and Setters */
public String execute(){
if (test1.length()>0)
assignValues();
return SUCCESS;
}
private void assignValues(){
if (test1.equals("A")){
test2 = "A was chosen, do something";
} else if (test1.equals("B")){
test2 = "B was chosen, do something else";
} else if (test1.equals("C")){
test2 = "C was chosen, what's next?";
}
}
}
The other doubts you are expressing in comments suggest that you may want to step back for a moment and read some Struts2 tutorial, to be sure of gaining the maximum from the framework.
If you have other fields in the same Form that you don't want to be affected, just declare a variable in the Action (with the Getter and the Setter), for each one of them: they will be preserved in the reloaded page, because they will be sent (because they're in form) with the submit, they will be injected through the Setter, they will be read back through the Getter and injected in the new page by the matching with their name and the Action variable.
Otherwise you could use AJAX, but I'd start from this.
And no, you can't nest forms.
Thanks to Andrea Ligios, i have the below solution to my issue.
jsp1 was changed as below
<s:form action="action2">
other fields
......
<s:select name="test1" list="{'Select','A','B','C'}"
onchange="javascript:document.forms[0].submit();"></s:select>
<noscript><s:submit value="populate test2 and test3"></s:submit></noscript>
<s:textfield name="test2"></s:textfield>
<s:textfield name="test3"></s:textfield>
.....
other fields
<s:submit value="submit1" action="action1"><s/submit>
</s:form>
struts.xml has following mappings
.....
<action name="action2" class="MyAction" method="populate">
<result name="success">/jsp1.jsp</result>
</action>
<action name="action1" class="MyAction">
<result name="success">/jsp2.jsp</result>
</action>
.....
MyAction has following code
public class MyAction extends ActionSupport{
//all field declarations
//Getters and Setters
public String execute(){
//do processing for jsp2 based on values from jsp1
return SUCCESS;
}
public String populate(){
//populate test2 and test3 from database based on value of test1
return SUCCESS;
}
}

Is there a way to pass a ServletRequest parameter to JavaScript?

Is there any way to pass the value of a parameter from a Servlet to JavaScript ?
the following didn't work.
var val = req.getParameter('valid');
This won't work because the ServletRequest only exists at the server and your JavaScript is running at the browser. It is easy to get the difference confused, because the code that runs on the server and the code that runs in the browser are very often both written in the same file (someServlet.java or somePage.jsp), so you have to remember how everything will sit at runtime.
What you can do, as a way of passing information that is retrieved from the request in the servlet to the JavaScript, is embed the data in the structure of the page on the server side. The page and its structure are then passed to the browser and the JavaScript has access to the full page structure on the client side. So you put something like this in the servlet:
<form name="data" action="" >
<input type="hidden" id="parmEmpId"
value='<%= request.getParameter( "EMPLOYEE_NUMBER" ) %>' />
<input type="hidden" id="parmServerName"
value="<%= request.getServerName() %>" />
</form>
And then, in your JavaScript, you can pull the data from the page:
var employeeId = $("#parmEmpId").val(); //Using jQuery
var server = $("#parmServerName").val(); //Using jQuery

best way to move items between ListBoxes in ASP.NET using javascript, then access results on server side

I am having a lot of trouble with a seemingly simple thing.
In an ASP.NET webform I have two ListBoxes, with Add and Remove buttons in between.
The user can select items in one ListBox and using the buttons, swap them around.
I do this on the clientside using javascript.
I then also have a SAVE button, which I want to process on the server side when the user is happy with their list.
Problems : First I was getting the following problem when I clicked SAVE :
*
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.
*
I read that one of the methods to get around this was to put my ListBoxes into an UpdatePanel, which I did, and I am getting further.
However, now the event handler for the button's Click event is not being run if the user has used the clientside javascript to alter the contents of the Listboxes. If the user has not altered the contents of the listboxes, the handler does execute.
What is happening?
Is my approach basically flawed and there might be a much better approach to this problem?
thanks for any help!
Here's the ASPX code :
<table>
<tr>
<td>
<asp:ListBox ID="fromListBox" runat="server" SelectionMode="Multiple" Rows="8" AutoPostBack="false"
DataSourceID="SqlDataSource1" DataTextField="FullName" DataValueField="UserId" CssClass="teamListBox">
</asp:ListBox>
</td>
<td>
<input id="btnAdd" type="button" value="Add >" /><br/>
<br/>
<input id="btnRemove" type="button" value="< Remove" /><br/>
<br/>
</td>
<td>
<asp:ListBox ID="toListBox" runat="server" SelectionMode="Multiple" Rows="8" AutoPostBack="false"
CssClass="teamListBox" DataSourceID="SqlDataSource2" DataTextField="FullName"
DataValueField="UserId" >
</asp:ListBox>
</td>
</tr>
</table>
Heres the javascript, using jquery....this works fine so is not really the problem :
$(document).ready(function () {
$("#btnAdd").click(function () {
$("#fromListBox option:selected").appendTo("#toListBox");
});
$("#btnRemove").click(function () {
$("#toListBox option:selected").appendTo("#fromListBox");
});
});
Just Go to your web config file in your application and Add enableEventValidation="false" in pages section.
The clean way would to be to use ClientScriptManager.RegisterForEventValidation Method.
Have also a look here.
You have to register the server control ID with all the possible values that can be posted by JavaScript by that control in Render Event of the page, for exampe:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation("fromListBox", "English");
ClientScript.RegisterForEventValidation("fromListBox", "Tamil");
ClientScript.RegisterForEventValidation("fromListBox", "Hindi");
ClientScript.RegisterForEventValidation("toListBox", "English");
ClientScript.RegisterForEventValidation("toListBox", "Tamil");
ClientScript.RegisterForEventValidation("toListBox", "Hindi");
base.Render(writer);
}
I think I had the same problem a while ago. I solved it by assigning the values of my listbox to a hidden text field and submitting the page all using javascript.
On the server side, I read the value of that hiddent textfield and parsed it.
It was an ugly client/server code, but it worked for me.

Categories

Resources