How to I reference the value of a selected item in dropdownlist? - asp.net-mvc-3

Pls look at following code
<select name="VideoType" id="VideoType" style="width:60px">
<option value="All">All</option>
<option value="Movie">Movie</option>
<option value="Show">Show</option>
</select>
<ul id="categories">
#foreach (var genre in Model)
{
<li>#Html.ActionLink(genre.Title,
"Browse", "Store",
new { Genre = genre.Title, VideoType = }, null)
</li>
}
</ul>
As U can see in the actionlink, how do i ref the selected value of dropdownlist? For eg: Movie.
Thanks

You can't do this because the ActionLink is generated on the server, whereas the selected value of the dropdown might change on the client. You will have to use javascript and subscribe to the onchange event of the dropdown and then modify the link of the anchor to include the selected value.

Like Darin said, you do it in javascript.
Add an id attribute to your anchor tag so that we can refer using that.
#Html.ActionLink(genre.Title,
"Browse", "Store",
new { Genre = genre.Title, VideoType = }, new { #id="link1"})
Then using javascript, change the link,
$(function(){
$("#VideoType").change(function(){
$("#link1").attr("href")="Store/"+$("#VideoType").val();
});
});

Related

Need to show the down arrow in dropdown list in ASP.NET Core MVC

Working on an ASP.NET Core 6 MVC app. I am created a dropdown using the select asp-for tag helper. But I am not seeing a dropdown down arrow. Also I want to set the top or particular value selected by default.
Below is code and image of a dropdown
<div class="col-sm-3">
<select name="products" class="form-control "
asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
</div>
Action Method code for ViewBag:
Public IActionResult Index()
{
var countries= _countries.getCountries();
//add an country item on the top of list.
countries.Insert(0, new Aircraft { Registration="0"});
//i used the country.name for value and item
var ddforAircraft = from country in countries
select new { id = country.name, name=country.name=="0"?"Item List":country.name };
// ddforAircraft.Append(new { id = "0", name = "" });
ViewBag.ddaircraft = ddforAircraft;
return View()
}
I found the answer, after Tiny Wang pointed me to the direction which really helped me to search the answer.
In order to see the dropdown down arrow I added a css class "form-select" without removing anything and I started to see the down arrow
<div class="col-sm-3">
<select name="products" class="form-control form-select-sm form-select " asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
</div>
Missing dropdown arrow resulted from the class form-control, I test in my side and I found the arrow can be seen by default until I add class="form-control " to my code:
removing this 2 options then the arrow appeared again, so it proved to relate to the class, you may need to update the style:
Then I use Jquery to change the default selected option when page is loading in my code, my selector has Id Country, then change the value(ListItem.Value):
<select asp-for="Country" asp-items="#(new SelectList(Model.Countries, nameof(ListItem.Value), nameof(ListItem.Text)))">
<option>Please select one</option>
</select>
#section Scripts{
<script>
$("#Country").val('Canada')
</script>
}

Select/Multiselect using choice.js in laravel livewire not working

I have using livewire and now I need to create select dropdown with a search option, and I came across choices.js choice.js link and follow this livewire with choice.js link I can make with work (but I have to use wire:ignore) for the select when the data is not dependent on others select (like fetch district after state is selected)
Now I need to fetch district after state is change, and of course i use wire:ignore because of styling and the district cannot display in the option list. If I didn't use wire:ignore then the style is breaking. For the very first time the district display based on state select without breaking any styles, after that district cannot updated even state is changed.
Below are my code for select state and district
<x-input.select wire:model="state" prettyname="state" :options="$allState" selected="('State')" placeholder="Select State*"/>
#if(!is_null($state))
<x-input.select wire:model="district" prettyname="district" :options="$allDistrict" selected="('District')" placeholder="Select District*"/>
#endif
and in Component
public function updatedState($state)
{
$this->allDistrict = District::where('state_id', $state)->pluck('id','name')->toArray();
}
The function updatedState() is trigger but the districts value cannot display in the blade file except the first time
the view component for <x-input.select /> is below
<div x-data wire:ignore x-init="() => {
var choices = new Choices($refs.{{ $attributes['prettyname'] }}, {
itemSelectText: '',
});
choices.passedElement.element.addEventListener(
'change',
function(event) {
values = event.detail.value;
#this.set('{{ $attributes['wire:model'] }}', values);
},
false,
);
let selected = parseInt(#this.get{!! $attributes['selected'] !!}).toString();
choices.setChoiceByValue(selected);
}"
>
<select id="{{ $attributes['prettyname'] }}" wire-model="{{ $attributes['wire:model'] }}" wire:change="{{ $attributes['wire:change'] }}" x-ref="{{ $attributes['prettyname'] }}">
<option value="">{{ isset($attributes['placeholder']) ? $attributes['placeholder'] : '-- Select --' }}</option>
#if(count($attributes['options'])>0)
#foreach($attributes['options'] as $key=>$option)
<option value="{{$key}}" >{{$option}}</option>
#endforeach
#endif
</select>
</div>
My question is how to get district value based on state data, and not breaking style and which can be searchable?
Thanks in advance

thymeleaf how to pass many objects?

how to pass many objects in one form? becouse like that not working.... help me please
<form class="form-control" action="#" th:action="#{'/'}" method="post">
<select>
<option th:each="city :${cities}" th:value="${city.getId()}" th:text="${city.getName()}"/>
</select>
<select>
<option th:each="category :${categories}" th:value="${category.getId()}" th:text="${category.getDescirption()}">
</option>
</select>
//this line isnt correct:
<a class="btn btn btn-primary btn-sm" href="#"
th:href="#{'/todo/done?id=' + ${city.id} + '&name=' + ${category.name}}">done</a>
</form>
You add each object as named model attribute. Example
#RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("cities", citiesRepository.getAll());
model.addAttribute("categories", citiesRepository.getAll());
return "message/list";
}
Personally I find it more readable to have single object as model attribute. That object has fields for each actual attribute.
See official documentation for more details https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
In your example you are not using th:each correctly.
You should have th:each as select level (not at option level) then refer to individual items in nested select elements.
like
<select th:each="city :${cities}">
<option th:value="${city.getId()}" th:text="${city.getName()}"/>
</select>
In your last example you are refering to ${city.id} and ${category.name} but city and category are not defined (probably thymleaf error message tells you that).
What exactly you want to achieve? Do you want to link with selected city and category? If so, you need separate model attributes like
selectedCity and selectedCatetory.

Pass dropdown text to controller

I have below dropdown, how do I retrieve the dropdown selected dropdown text (not value) on MVC controller upon clicking the submit button (httppost)?
<select id="detailThing" name="MyList">
<option value="BMI">ListDetail1</option>
<option value="BMI">ListDetail2</option>
<option value="BMI">ListDetail3</option>
</select>
Put the <select> in a form and submit it to the controller. You will need a model with a string variable to pass the value into/through.
public class MyModel
{
public String myValue { get; set; }
}
in the view put this line at the top;
#model MyProject.Models.MyModel
then create an html form and put your select inside and create a submit button;
#using (Html.BeginForm("MyControllerMethod", "MyController", FormMethod.Post, new { id = "myform" }))
{
<select id="detailThing" name="myValue">
<option value="BMI">Putrajaya</option>
<option value="BMI">Sepang</option>
<option value="BMI">Hulu Langat</option>
</select>
<button type="submit">Submit</button>
}
setting the 'name' of the select to 'myValue' will link its 'selected' value to the variable on the model and pass it to the controller when the form is submitted. Hope this helps!
Update:
change the values to be the same as the display text,
<select id="detailThing" name="myValue">
<option value="Putrajaya">Putrajaya</option>
<option value="Sepang">Sepang</option>
<option value="Hulu Langat">Hulu Langat</option>
</select>

Sending form field values to params hash - rails

I have a partial that I call in layouts/application.html.erb to display a form for a search. The user chooses values from the two select fields; then, should hit enter to render a view with search results.
Here is the partial:
** _search.html.erb:
<form name="classic">
<select name="countries" size="1" onChange="updatecities(this.selectedIndex)" style="width: 150px">
<option selected>Select A Brand</option>
<option value="usa">Opel</option>
<option value="canada">Cheverolet</option>
<option value="uk">Scoda</option>
</select>
<select name="cities" size="1" style="width: 150px">
</select>
</form>
<script type="text/javascript">
var countrieslist=document.classic.countries
var citieslist=document.classic.cities
var cities=new Array()
cities[0]=""
cities[1]=["Vectra|vectravalue", "Corsa|corsavalue"]
cities[2]=["Optra|optravalue", "Lanos|lanosvalue"]
cities[3]=["Octavia|octaviavalue", "Fleshia|fleshiavalue"]
function updatecities(selectedcitygroup){
citieslist.options.length=0
if (selectedcitygroup>0){
for (i=0; i<cities[selectedcitygroup].length; i++)
citieslist.options[citieslist.options.length]=new Option(cities[selectedcitygroup][i].split("|")[0], cities[selectedcitygroup][i].split("|")[1])
}
}
</script>
The javascript is just to filter the second select dropdown based on the first select dropdown. What I need to do is to send the values chosen in this form in the URL for params hash so that I can act on it in the controller and display the search results. I could use link_to.
How do I include the selected values from the form fields in link_to?
Your help is appreciated. Thanks!
Serialize the form and send the data to the server. The selected value is passed as the hashvalue where the key is the "id" for the select tag.

Resources