asp.net helper for DropDownList won't render correctly - asp.net-mvc-3

I'm attempting to get a dropdown list to select the correct value when the page loads.
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value"), new { #class = "selectbox", selected = Model.CounterpartyType })
However, when the page renders it always selects the first value in the dropdown list.
The html source for the page:
<select class="selectbox" id="CounterpartyTypeSelect" name="CounterpartyTypeSelect" selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">
<option value="5802239e-c601-4f1e-9067-26321213f6e6">Societa per Azioni (SpA)</option>
<option value="f8160341-4a69-436f-9882-4da31a78f1d5">Gesellschaft mit beshrankter Haftung (GmbH)</option>
<option value="977980f2-ebb2-4c2a-92c2-4ecdc89b248d">Sociedad Anonima (SA)</option>
<option value="cdbeb1d3-301b-4884-b65a-612ddd8306f3">Private Limited Company (Ltd)</option>
<option value="1fe68d96-f31b-4859-9869-8c76a5eb1508">Corporation (Inc)</option>
<option value="9c9e5722-ab59-4d1c-a0a3-91b42a3ee721">Limitada (LTDA)</option>
<option value="0cb57339-8705-4e3a-8f6a-95e9664962b7">Public Limited Company (Plc)</option>
<option value="0924d6f1-06a9-49a3-ac05-b3e2686a0e92">Partnership</option>
<option value="c8fbe021-a8f7-4e9d-ab38-dbeb5af5a631">Limited Liability Company (LLC)</option>
<option value="30d9e22b-34f5-43c5-8471-e614dbedb6a6">Aktiengesellschaft(AG)</option>
</select>
As you can see it is putting the "selected" attribute into the outer select tag instead of on the option that matches the Id. I have another select with identical parameters (except variable names of course) and it renders correctly this way. I do not want to use DropDownListFor<T> because I have a HiddenFor field that actually submits this value in the form and javascript that sets the value to match the Select choice. I've confirmed my database is storing the values that I set correctly. What is going on?

SelectList() has an overload for you to choose the selected item. You are adding it as an HTML attribute in the helper and those get rendered to the parent select tag.
Do this:
#Html.DropDownList("CounterpartyTypeSelect", new SelectList(ViewBag.CounterpartyTypeOptions, "DefaultId", "Value", Model.CounterpartyType), new { #class = "selectbox" })
Use the overload for SelectList that takes four arguments:
new SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue);

What's happening in the first line of your code new { #class = "selectbox", selected = Model.CounterpartyType } is you're providing the selected attribute as an HTML attribute of the parent select element.
So you see selected="977980f2-ebb2-4c2a-92c2-4ecdc89b248d" appearing in your first line of output, which btw doesn't do anything.
Also you're providing the value to search for in the Helper as a hardcoded string "value" instead of the actual value you need from the model. The browser will default to the first option since it can't find any value matching 'value'.
To fix this, provide Model.CounterpartyType as the third parameter to your SelectList parameter instead of 'value'.

Related

Save name instead of id from select component in laravel collective

I want to save the name of a department in the table employees, in the select component it displays the name but saves the id, so I think the problem is in it.
This is the select component:
{{Form::select('nombre_dep', $departamentos, null, array('class'=>'form-control', 'placeholder'=>'Asignar departamento'))}}
In my controller I have this for returning to the view:
$departamentos = departamento::pluck('nombre_dep', 'id');
In the model for employee I have this for relation:
public function departamentos(){
return $this->belongsTo('App\departamentos');
}
I expect to save in that field for example: production instead of 1 that could be id of the department
The selected answer is correct, but offers no explanation.
The issue is that you create your LaravelCollective Form::select so the integer id is sent in the ensuing request. You can verify this by viewing the source of the Form element in your rendered blade html. It currently will look like:
<select class="form-control" name="nombre_dep">
<option selected="selected" value="">Asignar departamento</option>
<option value="1">Production</option>
<option value="2">Department 2</option>
<option value="3">Department 3</option>
</select>
so when the action is triggered with (say) option 1 selected, your generated request simply has "nombre_dep" => "1".
You need to structure your form with the desired option value. like
<select class="form-control" name="nombre_dep">
<option selected="selected" value="">Asignar departamento</option>
<option value="Production">Production</option>
<option value="Department 2">Department 2</option>
<option value="Department 3">Department 3</option>
</select>
To do this, pass the $departamentos variable from your Controller like so:
$departamentos = array('Production' => 'Production', 'Department 2' => 'Department 2', 'Department 3' => 'Department 3');
and an easy way to do that (as the answer https://stackoverflow.com/a/56673741/8093282 stated):
$departamentos = departamento::pluck('nombre_dep', 'nombre_dep');
Perform the pluck specifying in the key parameter (the second parameter), the field from which you want to get the value to use in the value attribute of the select.
$departamentos = departamento::pluck('nombre_dep', 'nombre_dep');
Then when you pass the $departamentos array to the Laravel Collective select(), it will create an <option> element for each array element, using the array key as value attribute and the array value as option tag content.
{{ Form::select('nombre_dep', $departamentos) }}

JQGrid Drop Down Menu/Text Field in one

I have a requirement to load a set of pre-defined values from the database but also give a user ability to enter a custom values as well. Good example is here:
https://jsfiddle.net/api/mdn/
<label>Choose a browser from this list:
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
<option value="Microsoft Edge">
</datalist>
Is it possible to implement this feature in JQGrid?
This will only happen in the edit mode one per row. It should function exactly as as selecting from a drop down, only one value will be displayed and updated/saved. I will have to use is for only one column where each row will have a list of dynamic predefined values coming from the database.
Here is my start:
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
<option value="Microsoft Edge">
</datalist>
function myelem (value, options) {
var el = document.createElement("input");
el.type='text';
options.id = 'myBrowser';
el.setAttribute("list", "browsers");
return el;
}
The question is how to populate the datalist dynamically for each row based on the next column value and after exiting the edit mode save the selected value to the db?
Thank you,
If a value was previously saved for this column it should be displayed. When a user enters an edit mode the previously displayed value will be at the top (default) but the same set of predefined values should be available in the drop down with the option to enter a new custom value.
Thanks.
I found this very interesting and have created new article in our Guriddo Knowledge base where I explain in detail how to do this

Html.DropDownList selected value not working using ViewBag

Well, after a couple hours reading stuff over here, trying unsuccessfully all the solutions, also found this article that i thought it would save my life... nothing.
Long story short.
Here is my View (all combinations)
#Html.DropDownList("yearDropDown",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
#Html.DropDownList("yearDropDownxxx",(IEnumerable<SelectListItem>)ViewBag.yearDropDown)
#Html.DropDownList("yearDropDown",(<SelectList>)ViewBag.yearDropDown)
#Html.DropDownList("yearDropDown")
Here is my Controller
public ActionResult(int year)
{
var years = new int[] { 2007, 2008, 2009, 2010, 2011, 2012 }
.Select(x => new SelectListItem {
Text = x.ToString(),
Value = x.ToString(),
Selected=x==year }).Distinct().ToList();
years.Insert(0, new SelectListItem { Value = null, Text = "ALL YEARS" });
ViewBag.yearDropDown = new SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault());
return View();
}
Here is my rendered HTML. Selected nowhere to be found.
<select id="yearDropDown" name="yearDropDown"><option value="">ALL YEARS</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select>
Needless to mention, but i will, i checked in my Watch and SelectList actually has SelectedValue property populated with the selected year passed to the controller. But when i renders at the view, it goes to the first option.
Please, I need the solution for DropDownList, NOT for DropDownListFor. I am highlighting this because i saw other people here asking for the same help and bunch of people gave them instructions, and almost order them, to use DropDownListFor. There is a reason why i NEED to use DropDownList.
SOLUTION:
Look at my own answer.
However, here are the simple changes i made.
Controller:
ViewBag.yearDropDown = years;
View:
#Html.DropDownList("yearDropDown")
The problem may also be the name, see here.
In the Controller
ViewBag.PersonList= new SelectList(db.Person, "Id", "Name", p.PersonId);
In the View
#Html.DropDownList("PersonList",(SelectList)ViewBag.PersonList )
This will not work, you have to change the name, so it's not the same.
#Html.DropDownList("PersonList123",(SelectList)ViewBag.PersonList )
So change yearDropDown and it Will Work for you.
Best regards
Christian Lyck.
ViewBag.yearDropDown = new SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault());
Last parameter here is SelectListItem, but it must be selected value (string in your example)
SelectList Constructor (IEnumerable, String, String, Object)
I know its an old question, but I will share another solution since sometimes you have done anything correctly, but you can't see the selected value after a request and response, since your razor has bug maybe. In this condition, that I've had, you can use select-option using viewbag:
In controller I had:
ViewBag.MyData = GetAllData(strSelected);
...
and as a private function in controller I had:
private List<SelectListItem> GetAllData(List<string> selectedData)
{
return MyGetAll().Select(x =>
new SelectListItem
{
Text = x.Point,
Value = x.Amount.ToString(),
Selected = selectedPrizes.Contains(x.Amount.ToString())
})
.ToList();
}
And in .cshtml I had:
<select id="Amount" name="Amount" multiple="multiple">
#foreach (var listItem in (List<SelectListItem>)ViewBag.MyData)
{
<option value="#listItem.Value" #(listItem.Selected ? "selected" : "")>
#listItem .Text
</option>
}
</select>
I hope it will be useful for similar problems :)
Change the name of the ViewBag property to NOT match the name of the DropDownList.
Use ViewBag.yearDropDownDD instead of ViewBag.yearDropDown.
ALSO, you are creating the SelectList wrongly.
You need to pass the selected value not the array item:
ViewBag.yearDropDown = new
SelectList(years, "Value", "Text", years.Where(x => x.Selected).FirstOrDefault().Value);
The first place i should've gone to learn.... and i didn't.
Here is my solution
Thank you thou for your answers. Really appreciate it. I feel like shooting my own foot now. Two hours reading blogs and it took me 2 minutes to replicate this example and worked perfectly...

What is default value for "optionLabel" of the HTML DropDownList?

So if Set up a DropDownList where Text: "people names" (string)and Value:studentID (int). in my view like this (assuming myDDL is data from code-behind placed in the viewbag)
#Html.DropDownList("myDDL", (IEnumerable<SelectListItem>)ViewBag.myDDL,
"Select Stuff", new Dictionary<string,object>{
{"class","dropdowns"},{"id","myDDL"}})
What is the value of "Select Stuff" which is an optional label that appears at the beginning of the dropdown list?
I'd like the value because it if no value is selected then I'd like to get all the data.
Thanks!
It's empty and it's always the first option of the dropdown, so make sure that you are binding it to a non-nullable property in the postback action:
<select name="selectedValue">
<option value="">Select Stuff</option>
...
</select>
Also you seem to be using myDDL as both the first argument and the second of the dropdownlist helper which is wrong. The first argument is a property that would be used to get the selected value. The second is the available values and must be an IEnumerable<SelectListItem>.
So something like this would make more sense:
#Html.DropDownList(
"selctedValue",
(IEnumerable<SelectListItem>)ViewBag.myDDL,
"Select Stuff",
new { #class = "dropdowns", id = "myDDL" }
)
But what would really make sense and what I would recommend you is to get rid of this ViewBag and use a view model and the strongly typed version of this helper:
#model MyViewModel
...
#Html.DropDownListFor(
x => x.SelectedValue,
Model.MyDdlItems,
"Select Stuff",
new { #class = "dropdowns", id = "myDDL" }
)
It's the empty string. The documentation covers this (emphasis mine):
optionLabel
Type: System.String
The text for a default empty item.
This parameter can be null.
You can actually try adding a fake value into your List of object inside of your dropdown list which take inn value = "None"/"select stuff" and id = 0. In which it will help you to generate a fake value where user is able to select on the value in the dropdown list and you should be able to handle it on the backend code. Hope this helps.

MVC3 get Select Box Option Name as Well as Value

<select id="selectedSchool" size="3" multiple="multiple" name="selectedSchool">
#foreach (var item in ViewBag.pt)
{
<OPTION VALUE="#item.entityID">#item.name</OPTION>
}
</select>
on my page the user selects a school from the list of schools, each school has a unique ID which is needed and passed via the VALUE attribute, I also would like to pick up the name
(item.name) that was selected how can I resolve this info from my control Action Result?
public ActionResult ResultsSchoolsAttended(List<int> selectedSchool)
i iterate through the list of results, but I would aslo like selectedSchool.name to enter back in the db as 'display text'
how can i do this?
Well, MVC can only give you what is in the HTTP POST. And if you look at that, you will see that the <option> inner HTML isn't there. So you have only two choices:
Include it in the value in your markup, or
Look it up in your ResultsSchoolsAttended action based on the submitted value.
I'd pick the second, personally.

Resources