ASP.Net Core MVC SelectList not returning selected value to controller - drop-down-menu

For some reason all the selectlists are returning 0 to my controller. Below is my code, can someone please help?
View:
<div class="row align-items-start">
<div class="col-12">
<select app-for="customer.JobStage_Id"
asp-items="#(new SelectList(Model.jobStages, "Id", "Description",customer.JobStage_Id))"
class="selectpicker col-offset-1"></select>
</div>
</div>
Populate the list:
public IEnumerable<Lookups> getJobStages()
{
List<Lookups> jobStages = context.Lookups
.Where(s => s.Lookup_Type_Id == 15).ToList();
jobStages.Add(new Lookups { Id = 0, Description = "" });
return jobStages;
}
This is the view source code and everything looks correct so I don't understand why my model in my action has zeros for all selectlists.
<div class="row align-items-start">
<div class="col-12">
<select app-for="customer.JobStatus_Id" class="selectpicker col-offset-1"><option value="40">Dormant</option>
<option value="41">Waiting For POB POA Flex</option>
<option value="42">Sent Flex to Council / Awaiting Invoice</option>
<option value="43">Waiting for EST</option>
<option value="44">Waiting for Flex to be sent to Council</option>
<option value="45">Sent for Data Match</option>
<option value="46">Other</option>
<option selected="selected" value="0"></option>
</select>
</div>
</div>
Below is my full view followed by the full action:
[HttpPost]
public IActionResult UpdateCustomer(Customer customer)
{
if (ModelState.IsValid)
{
if (customer.PK_Id == 0)
{
customerRepository.add(customer);
}
else
{
customerRepository.update(customer);
}
}
return RedirectToAction("Index","Home");
}

You can try following code.
In your action:
public IActionResult ViewAction()
{
ViewData["JobStage_Id"] = new SelectList( context.Lookups.Where(s => s.Lookup_Type_Id == 15).ToList(), "Id", "Description");
return View();
}
In your view:
<select asp-for="customer.JobStage_Id" asp-items="ViewBag.JobStage_Id" class="selectpicker col-offset-1">
</select>
Please notice that your code is <select app-for="customer.JobStatus_Id",it should be asp-for,not app.

Related

Insert a Form value from a select in a dynamic url

While using laravel to create a movie catalog, I am trying to extract the value from an HTML Form and insert it in the URL.
The objective is that, from the main page which is:
http://127.0.0.1:8000/index/
I want it to extract an ID value from the form and insert it in the url:
http://127.0.0.1:8000/index/1
http://127.0.0.1:8000/index/2
http://127.0.0.1:8000/index/3
As each one is a dynamic view that will display each movie information from the database.
The form is already recognizing the ids and is displaying them in the select form in page, but I am not able to have that value used to insert it in the url as shown above.
Please help me, here is my code:
index.blade.php
<form action=" WHAT TO PLACE HERE??? " method="POST">
#csrf
<select name="selector">
<option value="" disabled selected> --- ID --- </option>
#foreach($movies as $movie)
<option value="{{ $movie->id }}">{{ $movie->id }}</option>
#endforeach
</select>
<button>Buscar</button>
</form>
web.php
Route::get('/index', 'App\Http\Controllers\MovieController#index');
Route::get('/index/create','App\Http\Controllers\MovieController#create');
Route::post('/index','App\Http\Controllers\MovieController#store');
Route::get('/index/{id}','App\Http\Controllers\MovieController#show');
Route::delete('/index/{id}','App\Http\Controllers\MovieController#destroy');
MovieController.php
class MovieController extends Controller
{
public function index() {
$movies = Movie::all();
return view('movies.index', ['movies' => $movies,]);
}
public function show($id) {
$movie = Movie::findOrFail($id);
return view('movies.show', ['movie' => $movie]);
}
public function create() {
return view('movies.create');
}
public function store(){
$movie = new Movie();
$movie->title = request('title');
$movie->synopsis = request('synopsis');
$movie->year = request('year');
$movie->cover = request('cover');
$movie->save();
return redirect('/')->with('mssg','La pelĂ­cula a sido registrada');
}
public function destroy($id) {
$movie = Movie::findOrFail($id);
$movie->delete();
return redirect('/index/');
}
}
Replace you form as:
index.blade.php
<form action="" method="POST" id="form_id">
#csrf
<select name="selector" id="selector">
<option value="" disabled selected> --- ID --- </option>
#foreach($movies as $movie)
<option value="{{ $movie->id }}">{{ $movie->id }}</option>
#endforeach
</select>
<button type="submit">Buscar</button>
</form>
Add script after this :
<script>
$('#selector').change(function(){
var selected_value = $(this).val();
$('#form_id').attr('action', 'http://127.0.0.1:8000/'+selected_value);
});
</script>
This will set your action dynamic as per selection with your select tag

Redering out a view based on dropdown value in Laravel 7

I would like to render a different view for 4 dropdown values in the controller. I'm new to PHP and Laravel and just starting to understand it.
dropdown html:
<div class="col-md-6">
<select name="employees" class="form-control #error('employees') is-invalid #enderror">
<option value="">-- {{ __('choose') }} --</option>
<option value="micro">1 - 5</option>
<option value="small">5 - 50</option>
<option value="medium">50 - 500</option>
<option value="large">500 +</option>
</select>
Controller:
class RegisterControllerStep2 extends Controller
{
public function form()
{
return view('auth.register_step2');
}
public function saveData(Request $request)
{
auth()->user()->update($request->only(['company_name', 'website', 'employees']));
return redirect()->route('home');
}
}
I want to redirect the user to another page other than home based on their selection from the employees dropdown above.
You need something like this
public function saveData(Request $request)
{
auth()->user()->update($request->only(['company_name', 'website', 'employees']));
if($request->employees==='micro'){
return redirect()->route('micro');
}
return redirect()->route('home');
}
Another thought I had on this is you could also do something like
return redirect()->route($request->employees);
As long as you had all your routes set up correctly with matching names to the values in your employees select
For giving a better experience I add this jquery function to justrusty's answer.
By doing this, it is not required for the user to press submit button for changes being applied.
Add a form with an id on the select:
<form action="something" method="post">
#csrf
<select id="employees" name="employees" class="form-control #error('employees') is-invalid #enderror">
<option value="">-- {{ __('choose') }} --</option>
<option value="micro">1 - 5</option>
<option value="small">5 - 50</option>
<option value="medium">50 - 500</option>
<option value="large">500 +</option>
</select>
</form>
Then add below jquery to the end of body section:
$('#employees').change(function() {
this.form.submit();
});
And at last, as justrusty said, redirect to the desired page in the controller:
if($request->employees==='micro'){
return redirect()->route('micro');
}

How to retrieve selected option value?

Hi guys new to laravel here! i am using selected option drop down list The First Select contains the countries and the second one has the states, now When i try to store the in database i am not getting the proper selected state instead i am always getting the first state in the second select Option!! i am using query Builder.
This is How i am retrieving Countries and states
public function store(Request $request)
{
$country = DB::table("countries")->where("id",$request->daira);
$state = DB::table("states")->where("country_id",$request->daira);
$daira = $country->get()->first()->name;
$impact = $state->get()->first()->commune;
dd($impact);
}
Note: dd($impact); Should be retrieving the selected state, instead it's retrieving the first value on the Selection List
So my Question is How do i get it to retrieve The proper Selected state !? Hope my question is clear Thanks in Advance.
Updated:
In the First Select option I have Countries name and in the second option i have
states each country has maximum 3 states, let's say Country A has 3 States A1,A2 and A3 And i want to select State A2 from the select option Value and instead of getting A1 by default like my case in the Question
Updated: I Am using VueJs
This is The form code
<template>
<div class="modal-body">
<div class="form-group">
<select name="direction" class="form-control">
<option value="">Selctionner Direction</option>
<option value="ENERGIE">ENERGIE</option>
<option value="HYDRAULIQUE">HYDRAULIQUE</option>
<option value="ENVIRONNEMENT"> ENVIRONNEMENT</option>
<option value="AMENAGEMENT">AMENAGEMENT</option>
<option value="P.T.T">P.T.T</option>
<option value="TOURISME">TOURISME</option>
<option value="TRANSPORT">TRANSPORT</option>
<option value="TRAVAUX PUBLICS">TRAVAUX PUBLICS</option>
<option value="EDUCATION">EDUCATION</option>
<option value="ENSEIGNEMENT SUPERIEUR">ENSEIGNEMENT SUPERIEUR</option>
<option value="URBANISME">URBANISME</option>
<option value="FORMATION PROFESSIONNELLE">FORMATION PROFESSIONNELLE</option>
<option value="SANTE">SANTE</option>
<option value="JEUNESSE-SPORTS CULTURE">JEUNESSE-SPORTS CULTURE</option>
<option value="PROTECTION SOCIALE">PROTECTION SOCIALE</option>
<option value="INFRASTRUCTURES ADMINISTRATIVES">INFRASTRUCTURES ADMINISTRATIVES</option>
<option value="HABITAT">HABITAT</option>
<option value="COMMERCE">COMMERCE</option>
<option value="LOGEMENT">LOGEMENT</option>
<option value="LOCAUX A USAGE PROFESSIONNELE">LOCAUX A USAGE PROFESSIONNELE</option>
<option value="FORET">FORET</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Daira:</label>
<select name="daira" class='form-control' v-model='country' #change='getStates()'>
<option value='0' >Select Country</option>
<option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
</select>
</div>
<div class="form-group">
<label>Selctionner Commune:</label>
<select name="impact" class='form-control' v-model='state'>
<option value='0' >Select State</option>
<option v-for='data in states' :value='data.id'>{{ data.commune }}</option>
</select>
</div>
<div class="form-group">
<label >Intitule :</label>
<input type="text" class="form-control" name="intitule" required>
</div>
</div>
</template>
And this is My Script
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data(){
return {
country: 0,
countries: [],
state: 0,
states: []
}
},
methods:{
getCountries: function(){
axios.get('/api/getCountries')
.then(function (response) {
this.countries = response.data;
}.bind(this));
},
getStates: function() {
axios.get('/api/getStates',{
params: {
country_id: this.country
}
}).then(function(response){
this.states = response.data;
}.bind(this));
}
},
created: function(){
this.getCountries()
}
}
</script>
can you post the result of dd($request->all()) ?
assuming your select name is daira and impact, you should be able to get the posted value with this:
public function store(Request $request)
{
$daira = $request->daira;
$impact = $request->impact;
}
I understand your issue first state returns because of when you passed country id it returns all the state related this country.
So that you need to pass state Id from state drop-down.
<select name="impact">
<option value="id">{{ STATE NAME }} </option>
</select>
And then you need to pass that state id in controller.
$state = DB::table("states")->where("id",$request->impact);
Hope you understand your queries
I assume $request->daira is country ID
public function store(Request $request)
{
//here you selected a country with provided country ID
//this returns Query Builder object
$country = DB::table("countries")->where("id",$request->daira);
//here you are returning all the states where the country_id is
//the provided country ID
//Note that this returns all the states (Query Builder object)
$state = DB::table("states")->where("country_id",$request->daira);
//You return `Illuminate\Support\Collection` then you got the first item
//from collection
$daira = $country->get()->first()->name;
//You returned all the states `Illuminate\Support\Collection`
//and you picked the first state from the collection,
//which is likely the first item in your
//form select field options
$impact = $state->get()->first()->commune;
dd($impact);
}
Because you didn't specify state_id, you will always get lists of all the states under the given country.
I assume table relationship is Country -> hasMany -> State
You need to add state_id as constraint, so only one state is picked
$state_id = $request->state
I assume you have state in your form
$state = DB::table("states")
->where("country_id",$request->daira)
->where('id', $state_id)
->first();
$impact = $state->commune

get value from select list to controller

I have a select list and I want to take the value selected and pass it to de controller, How can I do that?
this is my code
<select id="SelectImageType" onchange='submit();'>
<option value="0">Select Image Type</option>
<%foreach (var type in Model.ImageTypes)
{ %>
<option value="<%=type.Key%>"><%=type.Name%></option>
<%} %>
</select>
Thanks
The best why to do it is to use a DropDownListFor and then add the result into the model.
View:
<%: Html.DropDownListFor(m => m.SelectedImageType, new SelectList((IEnumerable)Model.ImageTypes, "Key", "Name"))%>
Controller:
ActionResult YourActionName(Model model){
var selectedImages = m.SelectedImageType;
}
Use name and in your controller use form collection to collect selected values
<select id="SelectImageType" onchange='submit();' name ="image">
<option value="0">Select Image Type</option>
<%foreach (var type in Model.ImageTypes)
{ %>
<option value="<%=type.Key%>"><%=type.Name%></option>
<%} %>
</select>
In your controller action
ActionResult YourActionName(FormCollection collection){
var selectedImages = collection["image"];
}

Many to many without crud

How to make a form for adding users, which have roles, I want to use something like in yabe example, but without crud...
User:
#ManyToMany(cascade=CascadeType.ALL)
public Set<Role> roles = new HashSet();
Role:
#ManyToMany(mappedBy="roles")
public Set<User> users = new HashSet<User>();
#{field 'user.email'}
<input id="${field.id}" name= "${field.name}" class="element text" maxlength="255" size="20" value="${field.value}"/>
#{/field}
...
<select multiple name="roles">
#{field 'user.roles'}
<option value="admin">admin</option>
<option value="user">user</option>
#{/field}
</select>
There's probably a better way to do it, and I'd be interested in finding out, but I do it like this:
<div class="field">
<select name="user.roles.id" multiple>
%{ models.Role.all().fetch().sort{ it.toString() }.each() { }%
%{ selected = false; user?.roles.each() { f -> if (f.id == it?.id) selected = true; } }%
<option value="${it?.id}"${selected ? 'selected'.raw() : ''}>${it}</option>
%{ } }%
</select>
</div>

Resources