I have a page that I want to create a drop down list, and post back to the same page that I am on now.
How can I do this?
One catch is, I want all the querystring values to be the same also, except for 1 which is what the drop down list will be overriding.
You can use both querystring and form variables in the same page if you want. If you use <form method="post"> and leave the action empty, it will post the form back to the current page, so that's one problem solved. There is one caveat: I'm not sure if leaving the action empty will keep the querystring parameters intact or not.
If not, you can try something like this: <form method="post" action="index.asp?<%= request.querystring %>"> (not sure about the exact syntax, the gist is that you will need to specify the current page and add the current querystring variables in the method).
In the ASP code on your page after posting you can check both request.form and request.querystring. request.form will contain your form post variables. request.querystring will contain the variables behind the ? in your URL.
HTH,
Erik
A Javascript method:
<html>
<head>
<script>
function jumpto(whatform, querykey) {
//get the url querystring
var url = window.location.search;
//the replace query
var queryrx = new RegExp("([?&])" + querykey + "=[^\&]+(?=&|$)", "gi");
//which item selected in dropdown
var index=whatform.pageselect.selectedIndex;
//if the first option, ignore it since it is blank
if (whatform.pageselect.options[index].value != "0") {
//is a query string available
if (url.length>0) {
//our query key is present
if (queryrx.test(url)) {
//now we replace the querystring from old to new
url = url.replace(queryrx, '$1' + querykey + '='+whatform.pageselect.options[index].value);
//clear out the question mark from the querystring
url = url.replace("?", '');
//our query key is not present, but there is querystring data
}else{
url = url.replace("?", '');
url = querykey + "=" + whatform.pageselect.options[index].value + "&" + url;
}
//no querystring data exists
}else{
url = querykey + "=" + whatform.pageselect.options[index].value;
}
//alert(url);
//this is the url we are getting bounced to
location = "mypage.asp?"+url;
}
}
</script>
</head>
<body>
<FORM NAME="form1">
<SELECT NAME="pageselect" ONCHANGE="jumpto(this.form, 'thequerykey')" SIZE="1">
<OPTION VALUE="">Choose a Page</OPTION>
<OPTION VALUE="pageA">First Page</OPTION>
<OPTION VALUE="pageB">Second Page</OPTION>
</SELECT>
</FORM>
</body>
</html>
If you want to go with an ASP Classic solution, you will need to use a function to clear your old value from your querystring
https://stackoverflow.com/a/1221672/2004151
And then print your querystrings as Hidden Input fields in your form (MyFunctionResultsExceptPageSelect below).
Something like:
<FORM ACTION="mypage.asp" METHOD="GET" NAME="form3">
<%=MyFunctionResultsExceptPageSelect("pageselect")%>
<SELECT NAME="pageselect" ONCHANGE="document.form3.submit()" SIZE="1">
<OPTION VALUE="">Choose a Page</OPTION>
<OPTION VALUE="pageA">First Page</OPTION>
<OPTION VALUE="pageB">Second Page</OPTION>
</SELECT>
</FORM>
<%
Function MyFunctionResultsExceptPageSelect(key)
Dim qs, x
For Each x In Request.QueryString
If x <> key Then
qs = qs & "<input type=""hidden"" name="""&x&""" value="""&Request.QueryString(x)&""" />"
End If
Next
MyFunctionResultsExceptPageSelect = qs
End Function
%>
If you want to get the current page instead of manually specifying it, then use the following.
In javascript snippet, use the answer here:
https://stackoverflow.com/a/5817566/2004151
And in ASP, something like this:
http://classicasp.aspfaq.com/files/directories-fso/how-do-i-get-the-name-of-the-current-url/page.html
Related
I'm trying to get my table in the index view filtered by certain values, for this I use a [HttpGet] Index method which creates 2 selectLists (one for each filter type). The filter button is supposed to take the the selected value of each list, and send them to the [HttpPost] Index method, which filters the table.
The problem is that that it doesn't "reset" the url when I filtered, so it keeps adding to the url everytime I change the filter.
Index Get (This one works fine)
[HttpGet]
public IActionResult Index()
{
IEnumerable<Lesson> Lessons = _LessonRepository.GetAll();
ViewData["Types"] = GetTypesAsSelectList();
ViewData["Difficulties"] = GetDifficultiesAsSelectList();
return View(Lessons);
}
Index Post (This one keeps adding /Lesson/Index everytime I click the filter button in my view)
[HttpPost]
public IActionResult Index(string filter, string filter2)
{
IEnumerable<Les> Lessons = null;
if (filter == null && filter2 == null)
Lessons = _LessonRepository.GetAll();
else if (filter != null && filter2 == null)
{
Lessons = _LessonRepository.GetByDifficulty(filter);
}
else if (filter == null && filter2 != null)
{
Lessons = _LessonRepository.GetByType(filter2);
}
else if (filter != null && filter2 != null)
{
Lessons = _LessonRepository.GetByType(filter2).Where(l => l.Difficulty == filter);
}
ViewData["Types"] = GetTypesAsSelectList();
ViewData["Difficulties"] = GetDifficultiesAsSelectList();
return View(Lessons);
}
View
<form action="Lesson/Index/" method="post">
<div class="form-inline">
<select id="difficulties" name="filter" asp-items="#ViewData["Difficulties"] as List<SelectListItem>" class="form-control">
<option value="">-- Select difficulty --</option>
</select>
<select id="types" name="filter2" asp-items="#(ViewData["Types"] as List<SelectListItem>)" class="form-control">
<option value="">-- Select type --</option>
</select>
<button type="submit">Filter</button>
</div>
</form>
This happens because action attribute in form tag contains relative url. The resulting url of request is current url + relative url and that's why Lesson/Index/ is appended to current url on request. Consider using absolute url by adding / at the beggining
<form action="/Lesson/Index/" method="post">
Since you are using ASP.NET Core you can also make use of asp-action and asp-controller
<form asp-action="Index" asp-controller="Lesson" method="post">
Or you can stick with relative url but you need to consider how the resulting url is built. So if you form is on /Lesson/Index view then can use the following action
<!-- empty action, or you can just remove the attribute completely -->
<form action="" method="post">
This will give you current url + relative url = "/Lesson/Index" + "" = "/Lesson/Index"
We have a three dropdown date of birth field in our form, which, right now is producing three separate error messages if the fields are left blank and user clicks submission.
We would like to either make it just one of those error messages, or show some other display beneath the submission button.
Any guidance would be fantastic!
Although not mentioned, I'd have to imagine you're using JavaScript to validate the form, and if so, try something like the following, whereby in your HTML you have a single span tag (or p) that's accessible via an id tag (like #error or something). In your JavaScript, simply set the #error tag to whichever error was last seen by the JavaScript. As you'll note below, if both "birth date" and "name" are missing, the span tag will only display the missing name error text. That said, you could easily concatenate the strings if need be.
Pseudocode (JS)
function validateForm() {
var isValid = true,
var myErrorText;
if (birth date is missing) {
isValid = false;
errorText = "You must enter a birth date";
}
if (name is missing) {
isValid = false;
errorText = "You must enter a name";
}
// Display the error message if the form is invalid
if (!validForm) {
$('span#error').text(myErrorText);
}
return validForm;
}
HTML
<form method="post" action="/whatever" onSubmit="return validateForm()">
<input type="text" id="birthDate" name="birthDate" >
<input type="text" id="name" name="name">
<button type="submit" id="submit" class="btn">Submit</button>
</form>
<span id="error"></p>
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"]);
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("¤cy_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.
I have a form that has a drop-down list of values and a submit button.
Currently, when you click on the submit button, a stored procedure is called and then the application generates a url and then the ActionResult is a Redirect to a new window. The url is based on the currently selected value in the dropdown list.
Our client wants another button that when clicked, will basically do the same thing, but FOR ALL VALUES in the drop down list.
Basically, on click, multiple windows will be opened, whose urls each based on a value in the drop down list.
I just started working with MVC and research confused me even more. I'm hoping someone can point me in the right direction.
Should I handle this via some sort of loop in javascript? How? Can you give some examples, please?
ASPX Portion:
<div id="MyContainer" class="select-report">
<%
using (Html.BeginForm(MyManager.Query.Actions.GenerateReport(null), FormMethod.Post, new{target="_blank"}))
{%>
<select name="SearchText" class="my-values-select">
<% foreach (var cc in Model.MyCentresList)
{%>
<option value="<%=Html.Encode(cc.Name) %>">
<%=Html.Encode(cc.Name) %></option>
<% } %>
</select>
<input type="hidden" name="SearchType" value="MyCentre" />
<input type="submit" value="Generate" name="EntityName" />
<% } %>
</div>
Code-Behind:
public virtual ActionResult GenerateReport(GenerateReportOperation operation)
{
string entityName = operation.SearchText;
int entityType = (int)operation.SearchType;
string requestID1 = <code here that calls a stored procedure, a value is returned>;
string requestID2 = <code here that calls a stored procedure, a value is returned>;
string urlString = <code here that contructs the URL based on the values of entityName, entityType, requestID1, requestID2>;
return Redirect(urlString);
}
You would have to use JavaScript to open new windows for each individual HTTP request.