I have a dropdown list in my html file.
I want the location (in the dropdown) to be automatically selected if it is present in the session object if session.
I hope you understand my question. I am new to mvc. Thanks
#if (Session["Location"] == null)
{
<select class="form-control" id="DeliveryLocation" name="DeliveryLocation">
<option value="" selected disabled hidden>Choose Your Location</option>
<option value="Aundh">Aundh</option>
<option value="Baner">Baner</option>
<option value="Balewadi">Balewadi</option>
<option value="Pimpri">Pimpri</option>
<option value="Nilakh">Nilakh</option>
<option value="Wakad">Wakad</option>
</select>
}
else
{
// i want code here to select value from dropdown as it is in location session
<pre> <select class="form-control" id="DeliveryLocation" name="DeliveryLocation">
<option value="" selected disabled hidden>Choose Your Location</option>
<option value="Aundh">Aundh</option>
<option value="Baner">Baner</option>
<option value="Balewadi">Balewadi</option>
<option value="Pimpri">Pimpri</option>
<option value="Nilakh">Nilakh</option>
<option value="Wakad">Wakad</option>
</select>
}
You should use SelectList and MVC's HTML Helpers to build your dropdown. It looks daunting if you're new to MVC, but it simplifies a lot of stuff for you.
In your current action method that loads this page:
ViewBag.DeliveryLocation = new SelectList(new[]
{
new { Text = "Aundh", Value = "Aundh" },
new { Text = "Balewadi", Value = "Balewadi" },
new { Text = "Pimpri", Value = "Pimpri" }
}, "Value", "Text", Session["Location"]);
There are a bunch of overloads for the SelectList class. So the above code creates a SelectList with the collection where Value property will be bound to option's value attribute and Text will be displayed as the option's text. The next parameter is selectedValue. In your case, you'd want to set to whatever is there in the Session["Location"].
You can also create a list of SelectListItem and put it in a ViewBag.
And then in your view,
#Html.DropDownList("DeliveryLocation")
That's it. So what happens here is, Razor generates a <select> element with name="DeliveryLocation". Then it looks for a DeliveryLocation property in the ViewBag. WE have set this in our controller and the options will be set accordingly.
Let's say, you have set ViewBag.DeliveryLocationList in your controller with the SelectList. Then you'd have to tell razor where to look for a SelectList. And since ViewBag is a dynamic object, you'd have to cast it.
#Html.DropDownList("DeliveryLocation", (IEnumerable<SelectListItem>)ViewBag.DeliveryLocationList, "Choose Your Location", new { #id= "DeliveryLocation" })
Here you have hardcoded the locations. In real applications, the option values like Locations will usually be fetched from the database. Then you don't have to make big changes if you use HTML helpers.
This link from Microsft docs has some great examples for beginners
100% work in your situation.
<select class="form-control" id="DeliveryLocation" name="DeliveryLocation">
<option #(Session["location"] == null ? "selected disabled hidden": "")>Choose location</option>
<option #((string)Session["location"] == "USA" ? "selected" : "")>USA</option>
<option #((string)Session["location"] == "Praga" ? "selected" : "")>Praga</option>
<option #((string)Session["location"] == "Paris" ? "selected" : "")>Paris</option>
<option #((string)Session["location"] == "China" ? "selected" : "")>China</option>
<option #((string)Session["location"]== "GB" ? "selected":"")>GB</option>
</select>
Related
I'm pretty new to this, and I am kind of running out of ideas to make this work.
Here's the situation; for a calculator-tool, I need to create a cascading drop-down menu where the second option selected corresponds with a value that then should be used as a variable in a formula. My issue currently is that I don't know how to assign a value to each option. I think I can figure out the rest of the code, but I've been stuck on this for a little while.
Here's the cascading drop-down menu I have so far. I changed the options, just to make sure it is in no way relevant to the project I'm working on. Let's, for the sake of clarity, say I need to assign the value of the car to the corresponding option, and use that to calculate the tax, which would be a certain percentage of the vehicle's value, later on.
<script>
function dynamicdropdown(listindex)
{
document.getElementById("Model").length = 0;
switch (listindex)
{
case "Mazda" :
document.getElementById("model").options[0]=new Option("Select Model","");
document.getElementById("model").options[1]=new Option("MX-5","MX-5");
document.getElementById("model").options[2]=new Option("RX-7","RX-7");
document.getElementById("model").options[3]=new Option("323","323");
document.getElementById("model").options[4]=new Option("626","626");
document.getElementById("model").options[5]=new Option("MX-6","MX-6");
break;
case "Subaru" :
document.getElementById("model").options[0]=new Option("Please select model","");
document.getElementById("model").options[1]=new Option("Impreza","Impreza");
document.getElementById("model").options[2]=new Option("Forester","Forester");
break;
case "Nissan" :
document.getElementById("model").options[0]=new Option("Please select model","");
document.getElementById("model").options[1]=new Option("350Z","350Z");
document.getElementById("model").options[2]=new Option("370Z","370Z");
document.getElementById("model").options[3]=new Option("Pulsar","Pulsar");
document.getElementById("model").options[4]=new Option("GT-R","GT-R");
document.getElementById("model").options[5]=new Option("Skyline","Skyline");
}
return true;
}
</script>
<div class="category_div" id="category_div">Select manufacturer:
<select name="category" class="required-entry" id="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select manufacturer</option>
<option value="Mazda">Mazda</option>
<option value="Subaru">Subaru</option>
<option value="Nissan">Nissan</option>
<div class="category_div" id="category_div">Select manufacturer:
<select name="category" class="required-entry" id="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select manufacturer</option>
<option value="Mazda">Mazda</option>
<option value="Subaru">Subaru</option>
<option value="Nissan">Nissan</option>
</select>
</div>
I do apologise if I've made any mistakes in changing the code to make it irrelevant to the project. As I said, I'm pretty new to this, so please be kind :)
You can pass en event to your function by putting this as an argument in the HTML (see the onchange in the HTML below). When we call the test function in the JavaScript code, the event argument is passed, which contains all the information about your dropdown menu. The event.value contains your selection, so you can use this to determine what value you would like to add.
JavaScript:
const test = (event) => {
let toAdd = 0
if (event.value == "Nissan") toAdd = 10
if (event.value == "Subaru") toAdd = 5
console.log(5 + toAdd)
}
HTML:
<div class="category_div" id="category_div">
Select manufacturer:
<select name="category" class="required-entry" id="category" onchange="test(this)">
<option value="">Select manufacturer</option>
<option value="Mazda">Mazda</option>
<option value="Subaru">Subaru</option>
<option value="Nissan">Nissan</option>
</select>
</div>
If you want to make your code smoother, you can destructure the value property at the start of the function, so you can write value in curley braces as an argument, rather than event. Then you can reference value going forward, instead of event.value...
const test = ({value}) => {
and...
if (value == "Nissan") toAdd = 10
Here's a pen with the code above
On my JSP Page have select field like this, Need to write a script- SCript should be like sending value from front end as per user selection. If selected is ALL US than all 4 entries should be selected, If all NJ than all inside NJ Should be selected and sent back to database in sql query.
<select multiple="multiple" class="form-control" id="SelectRegion" name="SelectRegion">
<option value="0" selected="selected">All(US)</option>
<option value="00001">All (NJ) </option>
<option value="123">Ship -1008 (NJ - 123) </option>
<option value="234">Ship -4120 (NJ - 234) </option>
<option value="00040">All (CA) </option>
<option value="345">Ship -1008 (CA - 345) </option>
<option value="567">Ship -4120 (CA - 567) </option>
</select>
If you're going to hardcode the specific values you want selected, then you can just set the values of your select tag directly using jQuery like so:
if ($("#SelectRegion").val() == 0) {
$("#SelectRegion").val(["123", "234", "345", "567"]);
}
Otherwise, you can add a class name to the elements for US and NJ and have some jQuery trigger whatever event you would like to select them dynamically:
if ($("#SelectRegion").val() == 0) {
$('.US').prop("selected", true);
}
If you don't necessarily need the selection reflected on the front end and just need the corresponding values, then you can again use class names to iterate through the values:
if ($("#SelectRegion").val() == 0) {
$(".US").each(function() {
// do something
});
}
I'm trying to make a chained dropdown that contain continent, region,country, province,city,district, and village, but i'm stuck at country.
my dropdown require me to use the id from database to chain all the dropdown, so to get the text name i usually using this method :
Country :
<select name="loc_country" class="loc_country loc5" id="loc_country" onchange="javacript: var valor2 = this.options[selectedIndex].text; document.getElementById('loc_country_real').value = valor2;">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
However this method doesn't work this time so i try another approach with :
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
and js :
$("#continent").change(function () {
$("#loc_country_real").val($('#loc_country').text());
});
and hoping when my select box with id="continent" changing, the value will update.
And that method also failed because the value given in "loc_country_real" doesn't match with selectbox "loc_country" (e.g.:when i selected europe on the continent selectbox, the loc_country select box will give me a list of european countries but the value in "loc_country_real" will be asian from country)
i need to make the text in "loc_country" and "loc_country_real" match but i have no idea how to do it, please help.
Try this:
Change your select's to have a VALUE matching the text you want E.G:
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">--Select--</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
You can then use document.getElementById('loc_country').value to get the selected option value
// Change `loc_country_real`'s value to match `loc_country` selected option
document.getElementById('loc_country_real').value = document.getElementById('loc_country').value;
Or the jQuery way:
$('#loc_country').change(function(){
$('#loc_country_real').val($('#loc_country').val());
});
Edit since you mentioned you cannot use value:
$('#loc_country').change(function(){
var textOfSelectedOption = $("#loc_country option:selected").text();
$('#loc_country_real').val(textOfSelectedOption);
});
I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});
So here is my code
<select id="BVT STUFF" onChange="jumpTo(getSelected(this));">
<option>HardRock Catalog</option>
<option value="http://link">BVT WIKI</option>
<option value="http://link">BVT CALENDAR</option>
<option value="https://link">Sustainment</option>
<option value="link">UVerse Dispatch Servlet</option>
This is a tool that I created for my team.
My problem is that I have the list "Title" as the first option and tried to give it a null value but whenever it is selected it tries to open a page. i.e. HardRock Catalog
Is there anything I could do with this to allow the list title to really have no value?
I'll suggest to add value="" for the first option. Then in your jumpTo function check
<option value="">HardRock Catalog</option>
function jumpTo(url) {
if(url === "") return;
// other stuff here
}
You could add selected and disabled attributes.
jsfiddle
HTML
<option selected="selected" disabled>HardRock Catalog</option>
You may try this
HTML :
<select onchange="jumpTo(this)">
<option value='0'>HardRock Catalog</option>
<option value="http:\\google.com">Goto Google</option>
<option value="http:\\yahoo.com">Goto Yahoo</option>
</select>
JS :
function jumpTo(select)
{
if(select.value != '0'){
// code goes here
location.href = select.value;
}
}
DEMO.