Pass html control values in Url.Action: MVC - html

I want to pass two parameters in #Url.Action.
View:
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="button" id="btnDownload">Download</button>
<button type="button" id="btnSearch">Search</button>
On Download button click, I am calling the method "ExportToExcel" in Masters Controller and also I need to pass two parameters. i.e. the selected value of select html and textbox value.
Now, I am using like below;
<button type="button" id="btnDownload" onclick="location.href='#Url.Action("ExportToExcel", "Masters", new { ddlSearchBy = #TempData["ddlSearchBy"], txtSearchValue = #TempData["txtSearchValue"] })'">Download</button>
Can I directly pass the html control values in #Url.Action?
Edited:
Controller:
[HttpPost]
public ActionResult ExportToExcel(string ddlSearchBy, string txtSearchValue)
{
var grid = new GridView();
grid.DataSource = from data in GetTaxMasterTable(ddlSearchBy, txtSearchValue)
select new
{
Code = data.taxCode,
TaxDescription = data.taxDescription,
ClassDescription = data.classDescription,
Location = data.locationShortName,
Zone = data.zoneName,
TaxValue = data.taxValue,
Tax = data.taxPercentage,
ModifiedDate = data.modifiedDate
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename = TaxMaster.xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return RedirectToAction("TaxMaster");
}
jQuery:
$("#btnSubmitDownloadExcel").click(function (e) {
var ddlSearchBy = $("#ddlSearchBy").val();
var txtSearchValue = $("#txtSearchValue").val();
$.ajax({
type: "POST",
url: "/Masters/ExportToExcel",
data: JSON.stringify({ "ddlSearchBy": ddlSearchBy, "txtSearchValue": txtSearchValue }),
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
alert("err");
alert(JSON.stringify(data));
}
});
});
This code is not downloading the Excel.

You cannot pass values from input elements using regular hyperlinks (Url.Action) without resorting to javascript.
But you can simply use a form with a method of GET.
<form action="Masters/ExportToExcel" method="get">
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="submit" id="btnDownload">Download</button>
</form>
Might want to use the Html.BeginForm() helper to generate the form for a more cleaner code, but the end result is the same.
Update - If you already have a form with another submit action
If you don't need to support IE 9 or below, you can use the formaction attribute to have the button change the action of the form.
Example:
<form action="SomeController/Search" method="get">
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="submit" id="btnSearch">Search</button>
<button type="submit" id="btnDownload" formaction="Masters/ExportToExcel">Download</button>
</form>
In this example, the form will do a get by default on SomeController/Search, when you click the btnSearch button. However, if you click the btnDownload button, the form will do a get request to Masters/ExportToExcel.
If you need to support IE below version 10, you need to use javascript to change the action of the form before you submit it.
Example using jQuery:
<form action="SomeController/Search" method="get">
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="submit" id="btnSearch" onclick="$(this).closest('form').attr('action','SomeController/Search');">Search</button>
<button type="submit" id="btnDownload" onclick="$(this).closest('form').attr('action','Masters/ExportToExcel');">Download</button>
</form>

Related

Redirect form to different URLs based on option selection

I want to redirect a form to different URLs based on option selection.
However, it will redirect the user to the URL without the click submit button.
How can I fix this?
<form action="#">
<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
<option value="https://www.google.com/" selected>Option1</option>
<option value="https://www.maybank.com/">Option2</option>
<option value="https://www.gmail.com/">Option3</option>
</select>
<input type="submit" value="Submit">
</form>
jquery
jQuery(function () {
jQuery("#selectbox").change(function () {
location.href = jQuery(this).val();
})
})
You can use submit method from jquery, you can use something like this
$(document).ready(function(){
$("form").submit(function(){
location.href = $('#selectbox').val();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form action="#">
<select id="selectbox" name="">
<option value="https://www.google.com/" selected>Option1</option>
<option value="https://www.maybank.com/">Option2</option>
<option value="https://www.gmail.com/">Option3</option>
</select>
<input type="submit" value="Submit">
</form>

Sending the form data using json formate

I am using the JSON format to send the form data using but there is found error that "The POST method is not supported for this route. Supported methods: GET, HEAD". Actually I am using API of getting hotels.For this send the request through JSON format but I got error.
This is my API url in which I am sending the request- https://cdn.grnconnect.com/static-assets/documentation/GRN_v3-1.3/hotels/search_and_availability_request/#search-and-availability-request
<form class="mt40 mb50" action="#" method="post" id="myForm">
<input type="text" name="searchCity" id="searchCity">
<input type="text" name="searchCityCode" id="searchCityCode">
<input type="text" name="nationality" id="nationality">
<input type="text" name="checkin" id="checkin">
<input type="text" name="checkout" id="checkout">
<select class="form-control" name="adult" id="adult" style="height:40px;">
<option value="">Adult Member</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button type="submit" class="awe-btn awe-btn-13 pr30 pl30 f16 bold font-hind"
id="find">Find
</button>
</form>
Script is-
$(document).ready(function(){
$("#find").click(function(){
var searchCity = $("#searchCity").val();
var adults = $("#adults").val();
var checkins = $("#checkin").val();
var checkouts = $("#checkout").val();
var nationality = $('#nationality').val();
// Checking for blank fields.
if (searchCity =='' || adults =='' || checkins =='' || checkouts =='' || nationality =='') {
alert("Please fill all fields...!!!!!!");
}
else {
$.ajax({
url:'https://cdn.grnconnect.com/api/v3/hotels',
type:'GET',
Data: {destination_code: search City, check-in: check-ins, check out: checkouts,client_nationality: nationality, cutoff_time: 5000, more_results: true,
hotel_info: false, rates: "comprehensive",rooms:adults},
success:function(data){
if(data['error'] == '0'){
window.location.href = 'https://cdn.grnconnect.com/api/v3/hotels';
}
},
error:function(e){
alert("error in request");
},
});
}
});
});
The route method is not specified in the route file for this route. Example:
Route::post('/hotels', 'HotelController#post')->name('hotel');
The URL is incorrect, the URL should be:
https://cdn.grnconnect.com/api/v3/hotels/availability
Instead of https://cdn.grnconnect.com/api/v3/hotels/

Make "name" not appear on url using a <select>

I'm writing a simple form, but I've encountered a problem. The form must generate an url like this
https://website.com/properties/hotelvinadelmar?locale=es&check_in_date=22-03-2019&check_out_date=25-03-2019&number_adults=4&number_children=9
The part after /properties/ (in this case, "hotelvinadelmar") is a code for an especific hotel, while the rest is the information the customer provide to check if there's availability.
I wrote this form:
Sucursal: <br>
<select name="test" id="id" required>
<option value="hotelvinadelmar?locale=es">Viña del Mar</option>
<option value="hotelsantiago1?locale=es">Nueva Providencia</option>
<option value="hotelsantiago2?locale=es">Providencia</option></select>
<br><br>
</select>
this almost work, but generates an url like this (...)/properties/?test=hotelvinadelmar?locale=es&number_adults=1(...)
Which is creating an url structured like this
[form action (the url I entered)][Option Name][selected Option Value]
But the thing must be like this
[form action (the url I entered)][selected Option Value]
How can this be achieved? Thanks in advance!
this is the correct behavior because the submitted form data test=hotelvinadelmar will be added after the URL
(...)/properties/, in order the achieve the desired result you can try to add action attribute to your form as <form action="/hotel"> and change the select as:
<select name="hotelname" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option></select>
<br><br>
</select>
the generated link will be: (...)/properties/hotel?name=hotelvinadelmar(...)
or you can use a javascript function with onSubmit event, for example:
<script>
function submitForm(){
var hotelName = document.getElementById('hotelName').value;
var param1Value = document.getElementById('id').value;
switch(hotelName) {
case 'hotelvinadelmar':
window.location.href = '/hotelvinadelmar?param1=' + param1Value + '&param2=' + (...);
break;
case 'hotelsantiago1':
window.location.href = '/hotelsantiago1?param1=' + param1Value;
break;
}
// stop submit
return false;
}
</script>
<form onsubmit="submitForm()" method="get">
<select id="hotelName" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option></select>
</select>
<input type="submit" value="submit"/>
</form>
Capture the submission event and update the form action attribute to append the hotel name to the submission path:
document.forms[0].addEventListener("submit", function (evt) {
let ff = evt.target;
ff.action = "/properties/" + ff.hotelname.options[ff.hotelname.selectedIndex].value;
});
You'll need remove the locale property from your select input. Simply add a hidden form element (or selectable option) to your form:
<input type="hidden" name="locale" value="es">
An example url:
https://website.com/properties/hotelvinadelmar?locale=es&hotelname=hotelvinadelmar&val1=one&val2=two
Here's a demonstration how the form action attribute can be updated:
document.forms[0].addEventListener("submit", function (evt) {
evt.preventDefault(); // demonstration only
let ff = evt.target;
ff.action = "/properties/" + ff.hotelname.options[ff.hotelname.selectedIndex].value;
console.log(ff.action); // demonstration only
return false; // demonstration only
});
<form action="/properties/" method="get">
<input type="hidden" name="locale" value="es">
Sucursal:
<select name="hotelname" id="id" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option>
</select>
<input type="hidden" name="val1" value="one">
<input type="hidden" name="val2" value="two">
<input type="submit">
</form>

Send the selected option using get to another page

I have a dropdown select option.There is button.On clicking the button the selected option must be send to another page "update.php" so that i can access the option there.In my case the new page is not loading or getting redirected to.
<select id=31 >
<option value="pending">pending</option>
<option value="accepted">accepted</option>
<option value="in progress">in progress</option>
<option value="cant">Cant be done</option>
</select></td>
<td><button id=i31 onclick="$.get("update.php",{id:31,s:$("#31 option:selected").text();})" >Submit</button></td>
If update.php is in another directory than your HTML make sure to use the absolute path to the file.
If you want the whole page to redirect you will want to use:
<form action="update.php" method="POST">
<select id="31" name="myFormOption" >
<option value="pending">pending</option>
<option value="accepted">accepted</option>
<option value="in-progress">in progress</option>
<option value="cant">Cant be done</option>
</select>
<button type="submit">Submit</button>
</form>
And in update.php catch the incoming POST with
if(isset($_POST['myFormOption'])) {
//Process Form Here
}
If you have to use AJAX I would then use window.location.href = "http://example.com"; after the call is successful.
Hope this helps :)
EDIT: Added AJAX Script
<script>
$('#i31').on('click', function() {
$.ajax({
method: 'GET',
url: 'update.php',
data: { id: 31, s: $("#31 option:selected").val() },
success: function() {
window.location.href = "http://example.com";
}
});
});
</script>

Use Value of Selected Item in List to Redirect Browser Accordingly [HTML]

Suppose I have a list box with different items, each with unique values, and an 'Enter' button below it. I want to be able to get the value of the selected item at the time of click, and then when have the button property:
ONCLICK="window.location.href='http://somewebsite.com/somefile.php?id="thisvalue"'"
So for example, something like----
<SELECT NAME = ParticipantList STYLE = "WIDTH: 187" SIZE = 18>
<OPTION VALUE='hi'> hello </OPTION>
<SELECT>
<INPUT TYPE="submit" VALUE="Info" ONCLICK="window.location.href='http://helloworld.com/this.php?="hi"'"/>
Can anyone help me figure this out? Much appreciated.
HTML forms are designed to do exactly this when their method is GET:
<form action="http://helloworld.com/this.php" method="get">
<select name="ParticipantList">
<option value="hi">Hello</option>
</select>
<input type="submit">
</form>
This will send the user to http://helloworld.com/this.php?ParticipantList=hi. No JavaScript required.
The Javascript
<script type="text/javascript">
function doAction(){
var selected = document.getElementById('ParticipantList').value;
if (selected == 'hello'){
window.location.href = 'http://somewebsite.com/somefile.php?id=1';
} else if (selected == 'bye'){
window.location.href = 'http://somewebsite.com/somefile.php?id=2';
} else {
alert('unknown option selected');
}
}
</script>
The HTML
<select name="ParticipantList" id="ParticipantList">
<option value="hello">hello</option>
<option value="bye">bye</option>
</select>
<input type="button" name="action" id="action" value="Submit" onclick="doAction()" />