What is default value for "optionLabel" of the HTML DropDownList? - asp.net-mvc-3

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.

Related

how to get selected value for Kendo DropDownList

I can't figure out how to determine which item is selected in the my kendo dropdownlist. My view defines it's model as:
#model KendoApp.Models.SelectorViewModel
The ViewModel is defined as:
public class SelectorViewModel
{
//I want to set this to the selected item in the view
//And use it to set the initial item in the DropDownList
public int EncSelected { get; set; }
//contains the list if items for the DropDownList
//SelectionTypes contains an ID and Description
public IEnumerable<SelectionTypes> ENCTypes
}
and in My view I have:
#(Html.Kendo().DropDownList()
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This DropDownList contains the values I expect but I need to pass the selected value back to my controller when the user clicks the submit button. Everything works fine except I don't have access to which item was selected from the controller's [HttpPost] action. So, how do i assign the DropDownList's value to a hidden form field so it will be available to the controller?
For anyone who found this wondering how to get the selected value in JavaScript, this is the correct answer:
$("#EncounterTypes").data("kendoDropDownList").value();
From the documentation: http://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist#methods-value
when select a value from a dropdown list, and in the selec event , we can get the selected value as following ,
#(Html.Kendo().DropDownList()
.Name("booksDropDown")
.HtmlAttributes(new { style = "width:37%" })
.DataTextField("BookName")
.DataValueField("BookId")
.Events(x => x.Select("onSelectBookValue"))
.DataSource(datasource => datasource.Read(action => action.Action("ReadBookDropDow", "PlanningBook").Type(HttpVerbs.Get)))
.OptionLabel("Select"))
javascript function like following ,
function onSelectBookValue(e) {
var dataItem = this.dataItem(e.item.index());
var bookId = dataItem.BookId;
//other user code
}
I believe this will help someone
Thanks
Hello I was just going through this problem,kept on searching for 2 hours and came up with a solution of my own.
So here is the line to fetch any data bidden to the kendo drop down.
$("#customers").data("kendoDropDownList").dataSource._data[$("#customers").data("kendoDropDownList").selectedIndex].colour;
Just change the id customers to the id you have given tot he kendo drop down.
Maybe you should be using the DropDownListFor construct of the Kendo DropDownList like so in your view:
#(Html.Kendo().DropDownListFor(m => m.EncSelected)
.Name("EncounterTypes")
.DataTextField("Description")
.DataValueField("ID")
.BindTo(Model.ENCTypes)
.SelectedIndex(Model.EncSelected)
)
This way, when you submit, it will be availble on the POST request and you won't need to put an hidden field anywhere.
BUT should you need to use the hidden field for some reason, put it there, subscribe the the select event of the dropdown list and put using JQuery (for instance) put the selected item on the hidden field.
It's your choice :)
If you want to read also out the text of the dropdown, you can get or set the value by using the following kendo function:
$('#EncounterTypes').data("kendoDropDownList").text();
REFERENCE TO THE DOCUMENTATION
Using this .val() as #Vivek Parekh mentions will not work - there is no function .val() in the kendo framework.
If you want you could use jQuery and get the value back: $('#EncounterTypes').val()
Updated DEMO
$("#EncounterTypes").kendoDropDownList().val();
You can get the selected item like following code and then use item.property to get further information
var selectedFooType = $("#fooType").data("kendoDropDownList").dataItem();
selectedFooType.name
//OR
selectedFooType.id

how to retrieve value of dropdown selection when form is not been submitted yet

I have following code
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), Model.SelectedID)
}
So user selection from this combo bind to SelectedID property of the model. My understanding is that this binding happen only when form is submitted. Let’s say from the same page, I need to do an AJAX call but at this point ) Model.SelectedID does not provide any value because form hasn’t been submitted yet (although user has selected something from drop down). Any ideas how to best deal with this situation?
You can use javascript.
var selectedValue = $("#IDs").val();
bind a change event to your DD
$("#DDL_ID").change(function(){
var currVal = $(this).val();
//do ajax
});
As others have pointed you would get this value with javascript on the change of the drop down list.
I wanted to point out however, that your understanding of the overload you are using for the drop down list is incorrect. This overload will display a default option box label.
For example you could prompt the users to select select something from the list:
#Html.DropDownListFor(m => m.IDs, new SelectList(Model. IDs), "Select Something...")
If you were to post the form in your example as is, you can see the selected item come across in the form. If your view model is setup in such a fashion the model binder would take over and bind this value to your "SelectedID" property.
[HttpPost]
public string DropDown(FormCollection form)
{
var selectedItem = form["IDs"];
return selectedItem;
}

MVC #Html.DropDownList

I have a #Html.DropDownList in the View. I like to default the value of what is select.
Note that #Html.DropDownList accepts a list. Not sure if there is a parameter to set it to a default value that is in the list.
If you want to pre select a value that is already in your list, then you need to set Selected = true on the SelectListItem.
There is also an option to pass an "option label" into the Html.DropDownList method but this is for rendering something like "Please choose a value from the list".
I believe something along these lines should work for you:
#Html.DropDownList("HtmlHelper", SelectList, new { #Value = valueToSelect });
Edit:
This should work for you:
#Html.DropDownList("Crd", (SelectList)ViewBag.CrdinatorSelectList, new { #Value = "James Brick" })
If you are wanting to get the Value from your ViewBag or ViewData you can try the following:
#Html.DropDownList("Crd", (SelectList)ViewBag.CrdinatorSelectList, new { #Value = ViewBag.Property })
#Html.DropDownList("Crd", (SelectList)ViewBag.CrdinatorSelectList, new { #Value = ViewData["Property"] })

MVC Html.DropDownList selected value being overriden by QueryString value

I am using a dropdownlist in my view like so:
#Html.DropDownList("ClientId", Model.AvailableClients, "-- None --")
Model.AvailableClients is an IEnumerable one of the item's Selected property is set to true. If in the query string for the page request includes "ClientId=" (as in its not set) MVC ignores my selected item. I assume this is because MVC is trying to be helpful and set the selected item automatically using the querystring, but I dont want this.
How can I prevent the querystring value from overriding my item's selected value?
If the name you give your DropDownList is already the name of an element in your model then DropDownList will automatically override the selected value with the model value. If letting ClientId determine the selected value isn't an option then the only solution I know is to rename the DropDownList with a name not included in the model.
#Html.HiddenFor(m => m.ClientId)
#Html.DropDownList("ClientIdNewName", Model.AvailableClients, "-- None --", new { onchange = "ClientId.value = this.value"})
This will keep the value in ClientId without making it the default selection value.

asp.net helper for DropDownList won't render correctly

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'.

Resources