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>
Related
I have a select element like this:
<select wire:model="state" >
<option value="">Choose a State:</option>
#foreach($state_list as $abbr=>$state)
<option >{{$state}}</option>
#endforeach
</select>
I'd like to have a default state that shows to the user. I've tried setting the $state property directly, and through the mount() method, and by using the SELECT attribute in the option.
As someone pointed out, I didn't have a value field. Additionally, in the actual code, this was a key on a property, so the field was actually name="bank[state]", so I had to add the state property in mount(), like this:
public function mount() {
$us_state_properties = ['address', 'bank'];
foreach($us_state_properties as $add) {
$this->{$add.".state"} = "Florida";
}
foreach($this->multi_us_state_properties as $add) {
$this->{$add.".0.state"} = "Florida";
}
}
And some fields were dynamically added within the form, as you can see in the second foreach loop.
I think it is because you forget the value in
<option value="{{$state}}">{{$state}}</option>
<select wire:model="state" >
<option value="">Choose a State:</option>
#foreach($state_list as $abbr=>$state)
<option value="{{$state}}">{{$state}}</option> <!-- this -->
<!-- <option value="{{$abbr}}">{{$state}}</option> --> <!-- or this ? -->
#endforeach
</select>
try to force test it
class FormSelectOption extends Component
{
public $state = 'FL';
...
}
Reference: https://laravel-livewire.com/screencasts/form-selects
I am trying to pass a value from the <option> of my <select> input to my livewire controller component and echo the value.
Livewire Blade View Component:
{!! Form::select('goals',$goals_plucked,null,[
'placeholder' => trans('classes.backend.forms.select_goals'),
'class' => 'custom-select',
'id' => 'goals',
'wire:change' => "goals(this.val)",
]) !!}
This get's me an output of null in my Livewire Controller Component
Livewire Controller Component
public $goals;
public function goals($goals)
{
dd($goals);
}
After watching some tutorials. I also tried using 'wire:change' => "goals($event.target.value)", which gave me an error of Undefined variable $event, obviously because it was not defined in main controller. I am not sure what am I doing wrong here.
What I am trying to do: Trying to create a flow just like select country then select state and then select city. via livewire. Before selecting a country the inputs of the select state and city won't be visible
I tried below code and it worked for me well. Just had to make sure I use normal html form inputs and dynamically add options to it by foreach loop. Also used mount() function for getting getting values and id's for select dropdowns.
Livewire Blade View Component:
<select wire:model="goal" name="goal" class="form-control" required>
<option value="">
{!! trans('classes.backend.forms.select_goals') !!}
</option>
#foreach ($goals as $goal)
<option value="{{ $goal->id }}">{{ $goal->goals }}</option>
#endforeach
</select>
Livewire controller component
public $goals;
public $goal;
public function mount()
{
$this->goals = Goals::all()->isActive();
}
public function updatedGoal($value)
{
dd($value);
}
just give wire:model="variable_name" to select in front end.
and in livewire controller there should be a public variable with same name. it will automatically get the value on select value change.
below is the example of same
<select class="custom-select border-0 shadow-none" id="enquiry_for" wire:model="enquiry_for">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
I am working on this ASP.NET Core MVC where I have this DropDownLisit which gets its values from Controller using ViewBag.DishTypes. However, upon submitting the form, the POST method is not getting the value of the option selected in the DropDownList. The code snippets are as follows:
Controller: GET Method
var allDishTypes = _context.DishType
.ToList()
.Select(dt => new SelectListItem { Value = dt.DishTypeId.ToString(), Text = dt.DishTypeName.ToString() }).ToList();
ViewBag.DishTypes = allDishTypes;
return View();
View
<form asp-controller="Home" asp-action="AddMenuItems">
<div class="row">
<label class="my-1 mr-2" for="inlineFormCustomSelectPref">Dish Type</label>
<div class="input-group">
<div class="fg-line form-chose">
<label asp-for="DishTypeId" class="fg-labels" for="DishTypeId">Dish Type</label>
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes" class="form-control chosen" data-placeholder="Choose Dish Type" required name="dishtype" id="dishtype">
<option value=""></option>
</select>
</div>
</div>
....
Controller: POST Method
[HttpPost]
public IActionResult AddMenuItems([Bind("DishTypeId, DishName, Cost")] Dishes dishesObj)
{
....
}
the POST method is not getting the value of the option selected in the DropDownList
Note that you specified a name=dishtype within your code. By this way, the field name is
always the same as this name attribute, i.e, dishtype instead of DishTypeId, which will not be recognized by ASP.NET Core by default.
To fix that issue, simply remove that attribute such that it uses asp-for to generate the name attribute automatically:
<select asp-for="DishTypeId" asp-items="ViewBag.DishTypes"
class="form-control chosen" data-placeholder="Choose Dish Type" required
name="dishtype" id="dishtype"
>
<option value=""></option>
</select>
I am building a Spring Boot app that calculates and displays Airbnb payouts on a monthly basis. Payout data is pulled in from the Airbnb Api, and user account information is stored in a database.
I have created a form where the user can specify the month and the listing to display the monthly payout. The user chooses the listing (the rental) from a dropdown menu. To display the names of the listings, a listingListDto attribute is added to the MVC model. A List of Listing entities is obtained from the database, and it is converted to a List of ListingDTO entities. This list gives the listingListDto.
When I reload the form page, the listings are readded to the dropdown, appearing twice, then three, four and more times.
How could I prevent this from happening?
I assume I could create a ListingListDTO entity, which would wrap the List of ListingDTOs, but I was hoping to be able to keep things simple, and use the List of ListingDTOs directly in the MVC model.
Here is the Controller method that displays the html form :
#RequestMapping(value = "payout", method = RequestMethod.GET)
public String payoutSelection(Model model, RedirectAttributes redirectAttributes) {
Long userId = sessionService.getCurrentUserId();
if (null == userId) {
return loginService.handleInvalidLogin("payout", redirectAttributes);
} else {
PayoutSelectionDTO payoutSelectionDto = new PayoutSelectionDTO();
LocalDate lastMonth = LocalDate.now().minusMonths(1);
payoutSelectionDto.setYear(lastMonth.getYear());
payoutSelectionDto.setMonth(lastMonth.getMonthValue());
Optional<User> user = userService.getUserById(userId);
model.addAttribute("payoutSelectionDto", payoutSelectionDto);
model.addAttribute("listingListDto", listingListDtoService.getListingListDTO(listingService.getListingsByUser(user.get())));
return "payout_monthpicker.html";
}
}
Here is the form which contains the dropdown of listings:
<body>
<div class="content-block">
<form action="#" th:action="#{/get_payouts}"
th:object="${payoutSelectionDto}" method="POST">
<h2>Kifizetések lekérése</h2>
<div class="content-group">
<select th:field="*{year}">
<option th:value="${payoutSelectionDto.year} -1"
th:text="${payoutSelectionDto.year} -1"></option>
<option th:value="*{year}" th:text="*{year}"></option>
</select> <select th:field="*{month}">
<option th:value="'1'" th:text="Január"></option>
<option th:value="'2'" th:text="Február"></option>
<option th:value="'3'" th:text="Március"></option>
<option th:value="'4'" th:text="Április"></option>
<option th:value="'5'" th:text="Május"></option>
<option th:value="'6'" th:text="Június"></option>
<option th:value="'7'" th:text="Július"></option>
<option th:value="'8'" th:text="Augusztus"></option>
<option th:value="'9'" th:text="Szeptember"></option>
<option th:value="'10'" th:text="Október"></option>
<option th:value="'11'" th:text="November"></option>
<option th:value="'12'" th:text="December"></option>
</select>
</div>
<div class="content-group">
<select th:field="*{listingId}">
<option th:each="listingDto : ${listingListDto}" th:value="${listingDto.airbnbId}" th:text="${#strings.abbreviate(listingDto.airbnbLabel,30)}"></option>
</select>
</div>
<div class="content-group">
<button type="submit" class="btn btn-primary btn-lg btn-block">Lekérés indítása</button>
</div>
</form>
</div>
</body>
Here is the ListingListDtoService. It has a way of screening for duplicates, so unless this is not doing what I think it is doing, no duplicates should be there from the result of running this service.
#Service
public class ListingListDTOService {
List<ListingDTO> listingDtoList;
public ListingListDTOService() {
this.listingDtoList = new ArrayList<>();
}
public List<ListingDTO> getListingListDTO(List<Listing> listingList) {
for(Listing listing : listingList) {
ListingDTO listingDto = convertListingToListingDTO(listing);
if(!listingDtoList.contains(listingDto)) {
listingDtoList.add(listingDto);
}
else {
System.out.println("identical Dto found in list while adding Dtos.");
}
}
return listingDtoList;
}
public ListingDTO convertListingToListingDTO(Listing listing) {
ListingDTO listingDto = new ListingDTO();
listingDto.setAirbnbId(listing.getAirbnbId());
listingDto.setAirbnbLabel(listing.getAirbnbLabel());
listingDto.setAirbnbPictureUrl(listing.getAirbnbPictureUrl());
return listingDto ;
}
}
Thanks to the coments from #Seth, this problem has been resolved.
Just copying from the comments to answer this.
If you don't have a good equals()/hashcode() method on ListingDTO, then your contains() call won't do what you want.
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.