I have situation where a client goes to a website to complete a webform and upon submission/click of an asp button performs two acts:
1) runs a jquery script that opens an iframe for an embedded form to a thirdparty service that gets information via a url created by the jquery also (in this case docusign)
2) runs a method to insert specific data about the submission to an sql database table.
It is my understanding that the OnClient has to fire prior to the OnClick as well as some sort of return/postback if I understand correctly is needed to fire the onclick/severside method. So my difficulty has been trying understand how best to get the serverside method to fire... Any thought would be greatly appreciated. At first thought adding some sort of return true function but do not see how this would work. Thanks for any input and forward guidance.
So currently my asp button OnClientClick calls the following jquery that opens an iframe... I cannot figure how to also have it postback to cause the Onclick event to fire as well? Unless I can have the jquery fire/called from behind?
(jquery used to open/embed form)
function $$(elem) {return document.getElementById(elem);} //simple id reference
//Powerform/Iframe Specifics
number_messages = 0;
var last_id = "";
function check_messages() { //check for messages from iframe
if (location.hash != last_id) {
last_id = location.hash;
number_messages++;
last_id = last_id.replace("_"," ");
last_id = last_id.substr(1);
last_id = last_id.substr(0,last_id.indexOf("&"));
var message_color;
var extra_text;
if(last_id=="Signing Complete" || last_id=="Viewing Complete"){
message_color="green";
extra_text = "";
}else{
message_color="red";
extra_text = "<p style='text-align:center'><button type='form.button' onclick='window.location=\"embedded.html\"' style='display:inline;'>Reload form?</button></p>";
}
document.getElementById("powerform").innerHTML = "<center><h3 style='color:"+message_color+";border:none;font-size:20px;text-align:center;'>" + last_id + "</h3><br/>"+extra_text+"</center>";
}
}
function open_embeddedform(form) {
var form_url = "https://demo.docusign.net/MEMBER/PowerFormSigning.aspx";
form_url += "?PowerFormId=" + $$("Powerformid").value;
form_url += "&UserName=" + $$("UserName").value;
form_url += "&UserEmail=" + $$("UserEmail").value;
//alert(form_url);
$$("powerform").innerHTML = '<iframe id="document" src="' + form_url + '" border="0"></iframe>';
}
setInterval(check_messages, 200);
Could you run the server side as a PageMethod or Web Service which the client side sends an Ajax request to with the information about the submission? That way you could also return a success to the user to display some completion message.
Make sure whatever your Onclientclick calls returns true. Check out This post for more detail.
Related
I have an aspx page (webforms) that is called from a jQuery Post method (which works fine), however the Response.Redirect method from the code behind does not reload the browser with the redirected URL. It does actually hit the URL, however.
I'm pretty sure this has something to do with the page being called from jQuery, but not sure why this behavior is happening.
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//lid = Validation.StripToGUID(ObjToGUID(Request.QueryString("lid")))
lid = Validation.StripToGUID(ObjToGUID(Request.Form["lid"]));
string sid = null;
if (lid.Length == 36)
{
//retrieve the link (and product data) from the database
LiveItem_Data.DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem o = new LiveItem();
o = LiveItem_Data.GetLive_ItemFromLID(lid);
if (HTTPStuff.RemoteFileExists(o.product_link))
{
Response.Redirect(o.product_link, true);
}
else
{
//generate an error
}
}
}
}
I stepped through the code and the product_link is working (manually cutting and pasting into a browser), and the remote page is being called (I'm testing the link with another site that has logging).
The browser however does not open (tried FF, IE, Opera, Chrome) the new URL.
The jQuery post:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID });
});
I verified that HTTPredirect feature is turned on in IIS Express (from Visual Studio 2012). Stumped!
I think from the jquery function, it will not redirect the page from server you will have to do this on client side itself i.e in the success part of the click function
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
$.post("redir.aspx", { lid: ListID }).success(function() {
//write the redirection code here
});
});
I don't think you're using post right. Post is for making a hidden service call and does not affect the browser window.
If you just want to redirect the browser window, and redir.aspx will accept either GET or POST, you can use window.location.href:
$('.popInfoHG').click(function () {
var ListID = $(this).parent().find('[id*=hidlid]').val();
window.location.href = "redir.aspx?lid=" + ListID;
});
If redir.aspx does not accept GET, I suggest you create a hidden form on your page (with an lid hidden input element) and post it programmatically.
I want to get data from a database and use it to login a user to a web site.
I have a wpf page that holds a web browser control. and I have this code that login user to web site which is written in php:
<form action='http://www.asite.net/index.php' method='post' name='frm'>
<?php
$user = $_GET['u'];
$pass = $_GET['p'];
echo "<input type='text' name='user' value='$user'>";
echo "<input type='text' name='pass' value='$pass'>";
?>
<input type='submit' name='submit' value='submit'>
</form>
How can I do this in wpf? As far as I can understand, I need to create an html and post it to site.
My questions:
1- How can I create such html in code?
2- How can I automatically submit it to the site (assuming I am doing this on constructor of a wpf user control).
As far as I understand, your goal is to log in and keep the session active inside the WebBrowser. If so, you have a few options:
First, navigate the WebBrowser to www.asite.net, to establish the session.
Then obtain the underlying WebBrowser ActiveX control and use IWebBrowser2::Navigate2 method, it has PostData parameter which allows to do an HTTP POST request.
Or, inject and execute some JavaScript which would use XHR to post the form the AJAX way.
Or, use WebBrowser.Document as dynamic to create a hidden form element, populate it and submit it, in the same way you'd do with JavaScript.
Or, use COM XMLHTTPobject to send a POST request, it shares the session with the WebBrowser.
You could also use some low level UrlMon API to send a POST request.
Updated, here is an example of creating and submitting a :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
NavigatedEventHandler handler = null;
handler = delegate
{
this.webBrowser.Navigated -= handler;
dynamic document = this.webBrowser.Document;
var form = document.createElement("form");
form.action = "http://requestb.in/tox7drto";
form.method = "post";
var input = document.createElement("input");
input.type = "text";
input.name = "name_1";
input.value = "value_1";
form.appendChild(input);
input = document.createElement("input");
input.type = "submit";
form.appendChild(input);
document.body.appendChild(form);
input.click();
};
this.webBrowser.Navigated += handler;
this.webBrowser.Navigate("about:blank");
}
}
Use the System.Net namespace, particularly the WebRequest and WebResponse objects.
See this previous answer, it should get you started:
How to programmatically fill a form and post a web page
The path is javascript path
var fileName = args.get_fileName();
lstImg.src = <%=GetListImageFilePath(fileName) %>
file name is error because it is javascript and not in .NET
how to put this argument in .NET Code
You'll need to use AJAX. One easy way to do it would be to use PageMethods. First, add a [WebMethod] attribute to your method:
[WebMethod]
protected static string GetListImageFilePath(string fileName)
{
This method must be static.
Then set EnablePageMethods="True" on your script manager. Then you can call your c# code from JavaScript like this:
var fileName = args.get_fileName();
PageMethods.GetListImageFilePath(fileName, function (path) {
lstImg.src = path;
});
You can't. The JavaScript runs on the client, and the asp.net code is on the server. You need to use some other way of communicating with the server eg: Ajax to a web service, a postback, etc
You simply can not do it because javascript is running at client side i.e on browser where as server code run at server. What you could do is change the your GetListImageFilePath function so that it returns the base URL for your image directory and then append the file name to create the image path.
var fileName = args.get_fileName();
lstImg.src = <%=GetListImageFilePath() %> + '/' + fileName;
For more information, like how server tags in Javascript are processed, I have answered a StackOverFlow thread here. Please have a look to clarify your doubt.
I think get_fileName() is server side function. So you can call it from the HTML directly.
Check these links
http://weblogs.asp.net/jalpeshpvadgama/archive/2012/01/07/asp-net-page-methods-with-parameters.aspx
http://stackoverflow.com/questions/7633557/asp-net-is-it-possible-to-call-methods-within-server-tag-using-eval
If you call the javascript function using RegisterStartupScript() or
RegisterClientScriptBlock() then these will be called in client side not in server side.
If you want to call the javascript function immediately in server side then declare an equivalent server side function.
add an ashx(http handler) in your website, then you can use lstImg.src = '/example.ashx?name=' + fileName.
public class ExampleHandler: IHttpHandler {
public void ProcessRequest (HttpContext context) {
var request = context.Request;
string fileName = (string)request.QueryString["name"];
// your logic
context.Response.Write(yourpath)
}
public bool IsReusable {
get {
return false;
}
}
}
Is there a way to assign/pass/copy a javascript variable to a server side variable in C#? For the sake of argument, let's say that I was able to parse some JSON for variables that I want to store and assign them on the client (ie. var = FirstName and var = 25 and var = someDateTime, etc) .
Javascript variables exist on the client so in order to get those values into the server you'll need to execute a request from the client. You probably want an approach called AJAX. AJAX involves Javascript making requests to the server in the background of your page. You'll set up a C# web page that expects these background requests. If you use a GET request then then place the variables in the query string of your AJAX request to your new C# page. If you want to use a POST request then you'll set parameters in the data that you post to your page.
Libraries like jQuery make this kind of thing pretty simple.
There's no direct way to access variables in client-side code from your server-side code.
An easy way, without writing handlers, ajax posts, etc., to accomplish this is to simply store the java script variable in a hidden text box and retrieve it on your post. You can also write back to the hidden field and feed your script with the value, e.g.
Markup
<asp:HiddenField runat="server" Id="JavascriptValue" value="0">
Script
<script>
var myValue = <%=JavascriptValue.Value%>
</script>
Server-Side
protected void Page_Load(object sender, EventArgs e)
{
string val = JavascriptValue.Value;
}
Write the value to a control (e.g. HiddenField) via JS and read that on the postback.
You can register hidden fields from code-behind on the Page_Load
if (this.Request.Form["myHiddenField"] == null) {
ClientScript.RegisterHiddenField("myHiddenField", ""); }
populate it with a script
ClientScript.RegisterOnSubmitStatement(this.GetType(),
MethodBase.GetCurrentMethod().DeclaringType.Name + "_myHiddenField",
"var res=document.getElementById('myHiddenField');if(res!=null){res.value='some value';}");
and read it on postbacks (also Page_Load)
var myValue = (!IsPostBack)
? null
: this.Request.Form["myHiddenField"];
what I did is save the javaScript variable in a cookie and then read it from C#.
JavaScript Code:
<script>
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
</script>
C# Code:
height of browser:#Request.Cookies["height"].Value;
I have a search page on my .NET 3.5 Web Forms site that redirects a user to an external site based on the user's search parameters. I would redirect to: http://www.site.com/search.aspx?searchterm=Hello.
But now they are changing the site so that the search parameter is passed as a POST parameter, and not in the query string. So the page is expecting "searchterm".
So not only do I need to redirect to the external page, I have to post data to the page as well. I have no idea how to do this and I don't know where to start.
Is this something I can do in Web Forms without some glitchy workaround? Or maybe it can be done using jQuery?
Most browsers will explicitely deny this. Doing a cross server post like this would lead to security issues.
You can create simple JavaScript function for execute POST redirect to external page (dynamicaly generate and initilaze form object and submit it).
For example (values pattern: a=1&b=2&c=3 ...):
function bind(pageURL, values) {
var form=document.createElement('form');
form.action= pageURL;
form.target='_blank';
form.style.display = 'none';
form.method = 'POST';
var valuesSplit = node.get_value().toString().split("&");
for (var i = 0; i < valuesSplit.length - 1; i++) {
var p = valuesSplit[i];
var ps = p.split('=');
addParam(form, ps[0], ps[1]);
}
document.body.appendChild(form);
form.submit();
}
function addParam(form,key,value){
var input= document.createElement('input');
input.name=key;
input.value=value;
form.appendChild(input);
}