#Html.DropDownListFor(x => x.SelectedProperty, Model.Property, "Please Select")
I have the above code in asp.net mvc3 to populate a dropdown list. Data populates but the selected item is the first item of the model result. I am trying to set default selected value as "Please select". How to do that?
In your controller action you should set the value of the SelectedProperty to the value of the item you want to preselect:
model.SelectedProperty = "5";
This obviously assumes that the Porperty contains such a value:
model.Property = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
new SelectListItem { Value = "4", Text = "item 4" },
new SelectListItem { Value = "5", Text = "item 5" },
new SelectListItem { Value = "6", Text = "item 6" },
};
By setting model.SelectedProperty = "5";, the item with Value="5" will automatically be preselected by the Html.DropDownListFor helper.
If on the other hand you want to have the "Please Select" default value being shown, make sure in your controller action that the SelectedProperty is set to null and not to some value contained in the items.
Related
I have a kendo combo box with two entries, say "Thing 1" and "Thing 2". I want "Thing 1" to be set by default.
Is there a preferred way to do this? I can't seem to find it, although I did set the placeholder attribute to "Thing 1" and it worked. The Kendo documentation says that placeholder is "The hint displayed by the widget when it is empty. Not set by default." Am I using placeholder incorrectly?
The optionLabel attribute (which I believe you refer to as the placeholder) is used to specify the text representing no selection. When that is chosen from the list, the selected item is null so is not the correct solution for setting a default, unless you wish the default selection to be null. The selection can be set programmatically by calling the select() method on the widget instance. The following for example will set the selection to 'Thing1'.
<div id="dropdownlist"></div>
<script type="text/javascript">
$("#dropdownlist").kendoDropDownList({
dataSource: [
'Thing1',
'Thing2',
'Thing3'
],
optionLabel: "None"
});
$("#dropdownlist").data("kendoDropDownList").select(1);
</script>
It is worth noting that this is not the only way to achieve this. My above example uses Imperative(JQuery) syntax to declare the dropdown. If you are using the ASP.NET MVC server wrappers, there is a Value attribute you can set in the declaration, for example:
.Value("1")
Finally, if you are using MVVM with declarative initialization, you can bind the selection to a value on a View Model. I haven't complicated my answer with an MVVM example since I assume you aren't using this mechanism.
<script>
$(function () {
var data = [
{ text: "12 Angry Men", value: "1" },
{ text: "Il buono, il brutto, il cattivo.", value: "2" },
{ text: "Inception", value: "3" },
{ text: "One Flew Over the Cuckoo's Nest", value: "4" },
{ text: "Pulp Fiction", value: "5" },
{ text: "Schindler's List", value: "6" },
{ text: "The Dark Knight", value: "7" },
{ text: "The Godfather", value: "8" },
{ text: "The Godfather: Part II", value: "9" },
{ text: "The Shawshank Redemption", value: "10" },
{ text: "The Shawshank Redemption 2", value: "11" }
];
$("#movies").kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
});
let combobox = $("#movies").data("kendoComboBox");//This "instantiates it"
combobox.value("The Godfather");
});
</script>
<input id="movies" />
Result:
I am working on an app in which I need to add items to kendo panelbar on button click.
These panels need to be expandabale/collapseble.
Is there a way to do this?
<ul id="panelbar"></ul>
<script>
$("#panelbar").kendoPanelBar();
var panelBar = $("#panelbar").data("kendoPanelBar");
panelBar.append(
[
{
text: "Item 1",
cssClass: "myClass", // Add custom CSS class to the item, optional, added 2012 Q3 SP1.
url: "http://www.telerik.com/" // link URL if navigation is needed, optional.
},
{
text: "<b>Item 2</b>",
encoded: false, // Allows use of HTML for item text
content: "text" // content within an item
},
{
text: "Item 3",
contentUrl: "http://demos.telerik.com/kendo-ui/content/web/panelbar/ajax/ajaxContent1.html"
},
{
text: "Item 4",
imageUrl: "http://demos.telerik.com/kendo-ui/content/shared/icons/sports/baseball.png",
expanded: true, // item is rendered expanded
items: [{ // Sub item collection.
text: "Sub Item 1"
},
{
text: "Sub Item 2"
}]
},
{
text: "Item 5",
// item image sprite CSS class, optional
spriteCssClass: "imageClass3"
}
]
);
</script>
Reference: http://docs.telerik.com/kendo-ui/api/javascript/ui/panelbar#methods-append
With the new kendo multiselect how would I add options to the list and make them selected?
For instance if I have a dropdown containing: 1,2,3 and I wanted to add 4 and 5 how do I do that? Do I have to destroy the multiselect, add the options and then reinit the multiselect?
Given the following multiselect definition:
var data =
[
{ text: "Africa", value: "1" },
{ text: "Europe", value: "2" },
{ text: "Asia", value: "3" },
{ text: "North America", value: "4" },
{ text: "South America", value: "5" },
{ text: "Antarctica", value: "6" },
{ text: "Australia", value: "7" }
];
var multi = $("#select").kendoMultiSelect({
dataTextField: "text",
dataValueField: "value",
dataSource: data
}).data("kendoMultiSelect");
You can use:
var values = multi.value();
For getting the list of values.
And for setting the value to South America (element with value 5) and "Asia" (element with value 3) use:
multi.value(["5", "3"])
If you want to add values to whatever it has then you need a little trick:
var multi = $("#select").kendoMultiSelect({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
value: ["1", "2", "3"]
}).data("kendoMultiSelect");
// Adding value 4 and 5 to current content
var values = multi.value().slice();
$.merge(values, ["4", "5"]);
multi.value(values);
Warning: If values 4 and 5 were already selected you will end up having them duplicated.
Just want to add some information about how to actually add new values to the multi-select.
As OnaBai points out, the code to add an item to the multi-select is
$("#SDropDown").data("kendoMultiSelect").dataSource.add({ Text: x, Value: y });
given the .cshtml
#(Html.Kendo()
.MultiSelect()
.Name("SDropDown")
.AutoBind(true)
.Placeholder("Select s...")
.DataTextField("Text")
.DataValueField("Value")
)
In order to add an item as entered in the multi-select hook the change event for the text input. Since this isn't uniquely identified, I use XPath to get the <input> element. This is hooked in document.ready (in .cshtml, so escape #):
$(document).ready(function () {
var node = document.evaluate('//select[##id="SDropDown"]/../div[contains(##class,"k-multiselect")]/input', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (node)
{
node.onkeypress = SChanged;
}
}
function SChanged(e)
{
// only append on enter
if (kendo.keys.ENTER == e.keyCode)
{
// updates multi-select data source
AddToOrganizations(this.value);
var multi = $("#SDropDown").data("kendoMultiSelect");
multi.dataSource.filter({}); //clear applied filter before setting value
// keep all currently selected items and append the user entered text
// (does not check for duplicates)
// Also, the new values can only be selected after the data source has
// been updated.
var values = multi.value().slice();
$.merge(values, [this.value]);
multi.value(values);
}
}
I have an editor template with a dropdown:
#Html.DropDownListFor(m => m.AdmissionState, new List<SelectListItem>()
{
new SelectListItem()
{
Text = "1",
Value = "1"
},
new SelectListItem()
{
Text = "2",
Value = "2"
},
new SelectListItem()
{
Text = "3",
Value = "3"
},
}, "- Select -")
I call it from the view:
#Html.EditorFor(m => m.Licenses)
In controller I have following code:
profile.Licenses.Add(new AttorneyLicenseModel()
{
AdmissionDate = "06/14/2012",
AdmissionState = "2",
AdmissionNumber = "asd",
});
profile.Licenses.Add(new AttorneyLicenseModel()
{
AdmissionDate = "07/16/2012",
AdmissionState = "5",
AdmissionNumber = "qwe",
});
For each of the licenses I see the fields with a data populated from the model, but not for the dropdown list - there is default value is checked. What am I doing wrong? ofcourse, the code with values is extremely simlified
Try like this:
#Html.DropDownListFor(
m => m.AdmissionState,
new SelectList(
new[]
{
new { Value = "1", Text = "1" },
new { Value = "2", Text = "2" },
new { Value = "3", Text = "3" },
},
"Value",
"Text",
Model.AdmissionState
),
"- Select -"
)
And if you are interested in understanding why my code works and yours not you could read the following answer I provided yesterday to a similar question: ASP.NET MVC DropDownListFor not selecting value from model
I'm populating a drop down list using this code (and it works fine):
#Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text"), "Please Select a Country")
Sometimes, this view also gets data of a pre-selected country, so I want to select that country.
I tried:
#Html.DropDownListFor(x => x.SelectedCountry, new SelectList(Model.Countries, "Value", "Text", "United States"), "Please Select a Country")
But this didn't work. I also tried the value of the item, and no luck.
What am I doing wrong?
Also, is there a way to access / modify that element after creation? (using C# not javascript)
Thanks!
There are 2 properties in the Model.Countries list: the Text and the Value. So if you want to preselect a given item in the dropdown you should use the value:
#Html.DropDownListFor(
x => x.SelectedCountry,
new SelectList(Model.Countries, "Value", "Text", "us"),
"Please Select a Country"
)
which assumes that in Model.Countries you have an item with Value="us".
As an alternative you could do this inside the controller action that is returning the view:
public ActionResult Foo()
{
var model = new MyViewModel();
model.Countries = new[]
{
new SelectListItem { Value = "fr", Text = "France" },
new SelectListItem { Value = "uk", Text = "United Kingdom" },
new SelectListItem { Value = "us", Text = "United States" },
};
model.SelectedCountry = "us";
return View(model);
}
and in the view you could simply:
#Html.DropDownListFor(
x => x.SelectedCountry,
Model.Countries,
"Please Select a Country"
)
which will preselect the element with Value="us" (the third one in my example).