Forward and pass data along in Asp.net - asp.net

In Asp.net Entity Framework I need to forward to another page and pass some data processed by the second page along.
In PHP I could do something like
<!-- page1.php -->
<form action="page2.php" method="POST">
<input type="hidden" name="id" />
<input type="submit" value="Go to page 2" />
</form>
<!-- page2.php -->
<?php
echo $_POST['id'];
?>
How can this be implemented in Asp.net?
Edit: There is a simple solution using Javascript and jQuery.
<!-- on page 1 -->
$('input[type=submit]').on('click', function (e) {
// Forward to browsing page and pass id in URL
e.preventDefault();
var id= $('input[name=id]').val();
if ("" == id)
return;
window.location.href = "#Request.Url.OriginalString/page2?id=" + id;
});
<!-- on page 2 -->
alert("#Request.QueryString["id"]");

There are, at least, two options:
Session state, like this:
Putting data into Session (your first page)
Session["Id"] = HiddenFieldId.Value;
Getting data out of Session (your second page)
// First check to see if value is still in session cache
if(Session["Id"] != null)
{
int id = Convert.ToInt32(Session["Id"]);
}
Query string, like this:
Putting the value into the URL for the second page as a query string
http://YOUR_APP/Page2.aspx?id=7
Reading the query string in the second page
int id = Request.QueryString["id"]; // value will be 7 in this example

There's a lot of ways to do this, take a look at this link for some guidance.
HTML page:
<form method="post" action="Page2.aspx" id="form1" name="form1">
<input id="id" name="id" type="hidden" value='test' />
<input type="submit" value="click" />
</form>
Code in Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string value = Request["id"];
}
MVC would look like...
#using (Html.BeginForm("page2", "controllername", FormMethod.Post))
{
#Html.Hidden(f => f.id)
<input type="submit" value="click" />
}
also, read through these MVC tutorials, you shouldn't blindly translate what you know in PHP to ASP.NET MVC, since you need to learn the MVC pattern too.

You can also use <form> with method="POST" in ASP.NET. And get value in code:
int id = int.Parse(Request.Form["id"]);

Related

How to Send Post request in java with javax.portlet.ActionResponse.sendRedirect method?

I want to POST to URL but following making it as GET , so How can I POST the
Object portletResponse = webAppAccess.getHttpServletRequest()
.getAttribute(Constants.PORTLET_RESPONSE);
if (portletResponse instanceof javax.portlet.ActionResponse) {
javax.portlet.ActionResponse actionResponse = (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(URL);
}
Have you tried to use RequestDispater instead of response.sendRedirect?
It retains the original request, without changing it.
So, it will remain POST if it was POST.
I have done this by using FORM POST method as follows.
webAppAccess.processPage("importedPage");
Added this imported Page in model :
<HTML>
<HEAD>
<title>New Page</title>
</HEAD>
<Body onload="">
<form id="FormID" method="POST" action="actionURL">
<input type="hidden" name="id" id="ID" value="<%=webAppAccess.getVariables().getString("ID")%>"/>
<noscript>
<p>Your browser does not support JavaScript or it is disabled.
Please click the button below to process the request.
</p>
<input type="submit" value="Proceed " name ="submit"></input>
</noscript>
<script>
document.getElementById('FormID').submit();
</script>
</form>
and then MVC controller mapping as follows:
#RequestMapping(value = {"/Details"}, method = RequestMethod.POST)
public String mthDetails(final Model p_model, #RequestParam(value = "id", required = false) final String p_ID){
//code for further logic using ID
}

How to add Paypal buy buttons to items in aspx page?

I am a newbie to paypal. I got a sandbox test item onpaypal and created an
item Buy button which is embedded html code.
Now whenever I insert the html code in the aspx page, it dosen't redirect to the paypal site.
Maybe because of the form tag that covers the html code. Here is the code for paypal buy button for an item:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="3GWR6RV47BCVE">
<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
I tried this code in a plain HTML file, and it worked. But as soon as I put it in a form runat server tag on aspx, it redirects the page to itself.
The problem is that ASP.NET pages define a form within which all the controls are placed (especially if you are using a master page) and HTML does not allow nested form tags.
There are several ways around this including using a normal ASP image button as described here.
You can also use an anchor link as described in this blog. However as noted by the author, the user can save the page source, edit it (e.g. change the price) and then reload it and click the link.
In fact any method that stores the information in the source of the webpage has potential to be abused. Therefore the approach I like, is to use a combination of an ASP image button and the anchor link approach but to implement this on the sever within the button click event:
1) In your ASP page define an image button where you want the PayPal button to go. You can set the ImageURL to the preferred button type provided by PayPal.
<asp:ImageButton
ID="PayPalBtn"
runat="server"
ImageUrl="https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif"
onclick="PayPalBtn_Click" />
2) Use the Click event of the button to generate the required information on the server side and then redirect the browser to the PayPal site.
protected void PayPalBtn_Click(object sender, ImageClickEventArgs e)
{
string business = "<insert your paypal email or merchant id here>";
string itemName = "<insert the item name here>";
double itemAmount = 123.451;
string currencyCode = "GBP";
StringBuilder ppHref = new StringBuilder();
ppHref.Append("https://www.paypal.com/cgi-bin/webscr?cmd=_xclick");
ppHref.Append("&business=" + business);
ppHref.Append("&item_name=" + itemName);
ppHref.Append("&amount=" + itemAmount.ToString("#.00"));
ppHref.Append("&currency_code=" + currencyCode);
Response.Redirect(ppHref.ToString(), true);
}
Disclaimer: It may still be possible for users to abuse this approach (although it is now a bit harder) so it is always best to check what has been paid before dispatching goods.
An ASPX page is like a giant HTML form. You need to close the ASPX form before the PayPal button code starts.
Like this:
<form name="default.aspx">
-- Page content
</form>
<!-- Close the form-->
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
-- button code
You can also try creating the button as a URL and hyperlink to some text or an image on your site - you can still use the PayPal button image. When you're viewing the button code within PayPal there should be a tab above it labeled "E-mail". Click that and you'll get a URL - if you're creating buttons with a drop-down menu or text field you cannot turn the button into a URL.
This is a hack way of doing it, but before the paypal code enter a closing form tag (This will close the asp pages form) then remove the closing form tag from the paypal code and allow the end of .net page end form tag to close the paypals form..
I did it using an iframe for each button
<iframe height="27" marginheight="0" src="/PayPalButton.htm?button_id=ABCXYZSSSSS" frameborder="0" width="120" marginwidth="0" scrolling="no"></iframe>
Here is the code inside PayPalButton.htm
<html>
<head>
<title>PayPal</title>
<script type = "text/javascript">
// function to get url parameter
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
// function to get button ID from url
function payPalButtonCode() {
var code = '<input value="_s-xclick" type="hidden" name="cmd" /> <input value="';
code = code + getURLParameters('button_id');
code = code + '" type="hidden" name="hosted_button_id" /> '
document.write(code);
}
function payPalButtonQuantity() {
var button_quantity_low = getURLParameters('button_quantity_low');
var button_quantity_high = getURLParameters('button_quantity_high');
var button_quantity_unit = getURLParameters('button_quantity_unit');
var button_quantity_units = getURLParameters('button_quantity_units');
var code = '';
var i;
if (button_quantity_low != 'No Parameters Found')
{
code = '<select name="quantity">';
for ( i = button_quantity_low; i <= button_quantity_high; i++) {
if (i > 1) {
code = code + String.format('<option value="{0}">{0} {1}</option>', i, button_quantity_units);
}
else {
code = code + String.format('<option value="{0}">{0} {1}</option>', i, button_quantity_unit);
}
}
code = code + '</select>';
}
else
{
code = '';
}
document.write(code);
}
function payPalButtonType() {
var code = '<input alt="PayPal – The safer, easier way to pay online." src="';
var button_type = getURLParameters('button_type');
if (button_type=='buy_now'){
code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif" type="image" name="submit" />';
}
else
{
//code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_subscribe_SM.gif" type="image" name="submit" />';
code = code + 'https://www.paypalobjects.com/en_GB/i/btn/btn_buynow_LG.gif" type="image" name="submit" />';
}
document.write(code);
}
String.format = function() {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
</script>
</head>
<body>
<form id="f1" method="post" action="https://www.paypal.com/cgi-bin/webscr" target="_top">
<script type="text/javascript">payPalButtonCode();</script>
<script type="text/javascript">payPalButtonQuantity();</script>
<script type="text/javascript">payPalButtonType();</script>
<img alt="" style="border: 0px solid;" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" />
</form>
</body>
</html>
For fixed-price buttons, there's a VERY easy, html-only workaround. Just copy the email-link provided by paypal, and create a very normal link using <a> ... </a>, which as content has the image that would normally appear in the <form> statement:
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3GWR6RV47BCVE" target="_top">
<img src="https://www.paypalobjects.com/it_IT/IT/i/btn/btn_buynowCC_LG.gif" border="0" title="submit" alt="PayPal – The safer, easier way to pay online." />
</a>
I've been searching for a solution today, so even if this thread hasn't been active lately, maybe this can be useful to someone else who wants to avoid code-behind.

ASP.Net MVC 4 Form with 2 submit buttons/actions

I have a form in ASP.Net and razor.
I need to have two ways of submitting said form: one that goes through the Edit action, and another that goes through the Validate action.
How should I go about doing this?
I don't mind using JavaScript for this.
EDIT:
Using the custom attribute I get this error.
The current request for action 'Resultados' on controller type 'InspecoesController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Validar(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController
System.Web.Mvc.ActionResult Resultados(System.Collections.Generic.ICollection1[Waveform.IEP.Intus.Server.Web.ViewModels.ResultadoViewModel]) on type Waveform.IEP.Intus.Server.Web.Controllers.InspecoesController
That's what we have in our applications:
Attribute
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
Actions decorated with it:
[HttpParamAction]
public ActionResult Save(MyModel model)
{
// ...
}
[HttpParamAction]
public ActionResult Publish(MyModel model)
{
// ...
}
HTML/Razor
#using (#Html.BeginForm())
{
<!-- form content here -->
<input type="submit" name="Save" value="Save" />
<input type="submit" name="Publish" value="Publish" />
}
name attribute of submit button should match action/method name
This way you do not have to hard-code urls in javascript
You can do it with jquery, just put two methods to submit for to diffrent urls, for example with this form:
<form id="myForm">
<%-- form data inputs here ---%>
<button id="edit">Edit</button>
<button id="validate">Validate</button>
</form>
you can use this script (make sure it is located in the View, in order to use the Url.Action attribute):
<script type="text/javascript">
$("#edit").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("Edit","MyController")");
form.submit();
});
$("#validate").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("Validate","MyController")");
form.submit();
});
</script>
If you are working in asp.net with razor, and you want to control multiple submit button event.then this answer will guide you. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".
#{
if (IsPost)
{
if(Request["btn"].Equals("button_A"))
{
Response.Redirect("PageA.cshtml");
}
if(Request["btn"].Equals("button_B"))
{
Response.Redirect("PageB.cshtml");
}
}
}
<form method="post">
<input type="submit" value="button_A" name="btn"/>;
<input type="submit" value="button_B" name="btn"/>;
</form>
Here is a good eplanation:
ASP.NET MVC – Multiple buttons in the same form
In 2 words:
you may analize value of submitted button in yout action
or
make separate actions with your version of ActionMethodSelectorAttribute (which I personaly prefer and suggest).
With HTML5 you can use button[formaction]:
<form action="Edit">
<button type="submit">Submit</button> <!-- Will post to default action "Edit" -->
<button type="submit" formaction="Validate">Validate</button> <!-- Will override default action and post to "Validate -->
</form>
<input type="submit" value="Create" name="button"/>
<input type="submit" value="Reset" name="button" />
write the following code in Controler.
[HttpPost]
public ActionResult Login(string button)
{
switch (button)
{
case "Create":
return RedirectToAction("Deshboard", "Home");
break;
case "Reset":
return RedirectToAction("Login", "Home");
break;
}
return View();
}
We can have this in 2 ways,
Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within
ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons
Or
Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code
if (Request.Form["btnSubmit1"] != null)
{
//
}
if (Request.Form["btnSubmit2"] != null)
{
//
}

asp.net javascript to db

have been struggling with this. Tried everything I can think of. Im using javascript to pass data to db, works fine with ints on another page but now with strings it wont work :s
#using (Html.BeginForm(null, null, FormMethod.Post, new{#id="manageForm"}))
{
#Html.AntiForgeryToken()
<span class="actions">
#T(User.Id.ToString()) #T(" ") #T(ViewData["Tag"].ToString())
<input type="hidden" name="tag" value="fr" />
<input type="hidden" name="id" value="3" />
#T("Follow")
</span>
}
Javascript
<script type="text/javascript">
function followTag() {
$('#manageForm').attr('action', '#(Url.Action("FollowTag"))').submit();
return false;
}
</script>
Controller
[RequireAuthorization]
[HttpPost]
public ActionResult FollowTag(int id, string tag)
{
_service.FollowTag(id, tag);
return RedirectToAction("TagPage","Detail", new
{
});
}
Data Access
public void FollowTag(int id, string tag)
{
DbCommand comm = GetCommand("SPTagFollow");
//user id
comm.AddParameter<int>(this.Factory, "id", id);
//id to follow
comm.AddParameter<string>(this.Factory, "tag", tag);
comm.SafeExecuteNonQuery();
}
route is setup fine and sql(stored procedure) executes perfect. Hopefully one of you can see something obvious
cheers
I think is a problem of mistyping, check your last <a> tag, you typed following.() in the onclick event, see that your javascript function is called followTag.
If that doesn't fix it, then get rid of that foolowTag function, you can specify the action and the controller in the form itself, like this:
#using (Html.BeginForm("FollowTag", "YourControllerName", FormMethod.Post)) {
...
//Delete this line
//#T("Follow")
//This submit button will do the job
<input type='submit' value='#T("Follow")' />
}
That should do it. If you are using the anchor tag just for styling that's ok, otherwise you should use the other way, I think is clearer and besides it takes advantage of razor's great features.

POST data getting 'lost' somewhere

UPDATE
So it turns out internet exploder's stranglehold on "security" to "make up" for being so bad at security was causing my problems. I should have checked that out first haha. Thanks everyone for the input, it has given me ideas on how to optimize my application :D
I am writing a web app (in ASP.NET 3.5) that integrates with a platform app. The platform app takes the user's credentials and puts them into an "empty" HTML page that consists of a form with hidden items containing said credentials and POSTS to the webapp (default.aspx):
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JSCRIPT>
function OnLoad(){
try {
document.form1.submit();
}
catch(e){
}
}
</SCRIPT>
</HEAD>
<BODY OnLoad="OnLoad()">
<FORM ACTION="http://localhost:51816/gs_ontheweb/default.aspx" METHOD=POST NAME=form1 TARGET="_NEW">
<INPUT TYPE="HIDDEN" NAME="ClientID" VALUE="123456">
<INPUT TYPE="HIDDEN" NAME="Password" VALUE="2830088828">
<INPUT TYPE="HIDDEN" NAME="PracType" VALUE="051">
<INPUT TYPE="HIDDEN" NAME="Encrypt" VALUE="12345620081111">
</FORM>
</BODY>
</HTML>
When my default.aspx page gets loaded up, it calls the following function:
Dim ClientID As String = Request.Form("ClientID")
Dim PassWord As String = Request.Form("Password")
Dim PracType As String = Request.Form("PracType")
Each one of them result in empty strings. Any ideas on why this is happening? Thanks in advance.
EDIT: Is there something I need to configure in my web.config file to make this work properly? Request.Params("<param name>") does not work.
Your issue is the "Target" property on the Form. Why is this here?
(I also took the liberty of cleaning your HTML up a little)
<html>
<head>
<title>Test JS Post</title>
<script type="text/javascript" language="javascript">
<!--
function OnLoad(){
try
{
alert("Posting...");
document.form1.submit();
}
catch(e)
{
alert("ERROR!");
alert(e);
}
}
//-->
</script>
</head>
<body onload="OnLoad()">
<form action="http://localhost:49684/Default.aspx" method="post" name="form1">
<input type="hidden" name="ClientID" value="123456" />
<input type="hidden" name="Password" value="2830088828" />
<input type="hidden" name="PracType" value="051" />
<input type="hidden" name="Encrypt" value="12345620081111" />
<h1>This is in the form. Submit me here:</h1><input type="submit" value="foo" />
</form>
</body>
</html>
In the code behind of Default.aspx:
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each value As String In Request.Form.Keys
Debug.WriteLine(String.Format("{0} = ""{1}""", value, Request.Form.Item(value)))
Next
End Sub
That HTML is just on the user's harddrive? Maybe the browser security won't let that POST because it's deemed to be a risk.
As a test -- take that exact HTML file and put it on your webserver and then browse to it. If it works, might be the browser refusing to send the data. You could check with Fiddler (for IE) or Firebug in FireFox.
Why not use System.Net.WebClient?
Some sample code (sorry, it's C#. Looks like your looking for VB. I can't translate quickly.)
System.Net.WebClient wc = new System.Net.WebClient();
byte[] b;
byte[] res;
string formdata = "text=test text&password=secret&checkbox=on&textarea=a longer text sentence&submit=submit";
// encode the form data string into a byte array
b = System.Text.Encoding.ASCII.GetBytes(formdata);
// set the content type for a form
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// POST and get data
res = wc.UploadData("http://localhost:51816/gs_ontheweb/default.aspx", b);
//convert the return page from byte[] to ascii
string s = System.Text.Encoding.ASCII.GetString(res);

Resources