My DropDownList is bound with public List<SelectListItem> CountryList { get; set; } Model's property as #Html.DropDownListFor(m => m.CountryCode, Model.CountryList, "-- Select --"). CountryCode is a short property to hold the code of the Country. How can i achieve
1- Show both Code and Name of the country in the DropDownList as "CountryCode - CountryName"
2- Receive both Code and the Name of selected Country as bounded to the Model passed to the Action. In other words, the type of the CountryCode is SelectListItem rather than short
PS. No scripting
1- Show both Code and Name of the country in the DropDownList as
"CountryCode - CountryName"
Got help from Creating a DropDownList helper for enums. Now the DropDownList is showing items as 0001 - Country Name but it is not keyboard friendly because end user should type 0001 to select Country Name rather than typing cou.... And selected Text has to be parsed to separate Value and Text, though not end user's headache but not ideal.
Working and waiting for the answer of second question...
Related
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
I have a form that has several controls in it. I added data annotation to display an error message to the user when the required field are left empty. The TextBoxes and other controls display the message, which is an "*" before the label name, but the dropdownlist does not not. Once the user get rid of all the error messages and click on submit again, then, the message for the dropdown box is display. How do I force the dropdown box to display the message at the same time with the textbox?
Additional information:
Here is a sample of my data annotation:
[MetadataType(typeof(UserMetaData))]
public partial class UserMeta
{
}
public class UserMetaData
{
[Required(ErrorMessage = "*")]
public int GenderID { get; set; }
//The gender ID is displayed in a dropdown
list with "Select" as the default option. Then, it has all the other genders
showing in the dropdown once it is clicked on.
[Required(ErrorMessage = "*")]
public DateTime DataOfBirth{ get; set; }
}
In my view, I am using
#Html.ValidationMessageFor(model => model.DataOfBirth) //This is working fine.
#Html.ValidationMessageFor(model => model.GenderID)
//Here is the dropdown
#Html.DropDownList("GenderID", null, "Select", new { style = "width:200px;", onchange = "ValidateDropdown()" })
//This is the one that is not working as expected. I could get it to work using javascript, but I am trying not to it if I there is a way to get it to work properly using data annotation.
Thank in advance for your help.
I could not get it to work properly on the server side. As a result, I had to write a JQuery function that does the validation for the dropdown on the client side. Then, I do the post only if there is a selection on the dropdown.
This is pared down a bit, but essentially I've got a model that looks something like this:
public class PersonCreateEditViewModel
{
public string Title { get; set; }
public IEnumerable<SelectListItem> Titles { get; set; }
}
and on my edit page I want to display the person's current title in a DropDownList so we can change their title. That code looks like this:
#Html.DropDownListFor(model => model.Title, new SelectList(Model.Titles, "Value", "Text", Model.Title))
and I populate it in my action like so by retrieving a bunch of strings:
IEnumerable<SelectList> titles = somelistoftitles.Select(
c => new SelectListItem
{
Value = c,
Text = c
};
var viewModel = new PersonCreateEditViewModel()
{
Title = model.Title,
Titles = sometitles
};
return View(viewModel);
and this populates the DropDownList with the values but does not select the person's current title. So, I'm obviously doing something wrong here. Looking at the underlying html, I see that the selected attribute is not set for the option corresponding to the person's Title. I thought that specifying Model.Title there as the third argument would select it.
Ideas?
Update
I added the setting of the Selected property as qntmfred suggested below, and that'll set the right one in the list to true but the <option> doesn't have the selected attribute on it.
SOLVED
So, this was subtle. I just so happened to have a ViewBag entry named "Title" - something like this:
#{
ViewBag.Title = "Edit Person"
}
and this evidently caused the selection to not work since my model has a "Title" property as well. I solved the problem by renaming the property.
SOLVED
As I wrote at the end of my question, this wasn't an obvious thing. I just so happened to have a ViewBag entry named "Title" - something like this:
#{
ViewBag.Title = "Edit Person"
}
and this evidently caused the selection to not work since my model has a "Title" property as well. I solved the problem by renaming the property.
Way too much time wasted on this problem this morning.
Lesson learned.
You need to set the Selected property on your SelectListItem
IEnumerable<SelectList> titles = somelistoftitles.Select(
c => new SelectListItem
{
Value = c,
Text = c,
Selected = (c.Equals(model.Title))
};
I am using html.textbox for 2 of my datetime field because I need to format them in a specific format but i don't know how to do it by html.textboxfor.
However, I realise i need to have the textboxfor for the validation in my model class to work:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
Any idea how can I change my Html.Textbox below into Html.TextBoxFor with the same setting??
#Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
#Html.ValidationMessageFor(model => model.ExpiryDate)
Appreciate any help... Thanks...
You don't really need to use TextBoxFor() for validation to work. If your TextBox has the same id as a field in the model, the model binder will pick it up. If you're talking about to get the unobtrusive validation features, you can always manually add the data-* attributes to your TextBox.
However, in this case it sounds like what you really want is a custom editor, using EditorFor(). It's a bit more work, but it will allow you to actually enforce the date/time formatting by giving the user something like a date/time picker control. The basic idea is:
Create a partial view called DateTime.cshtml that is bound to model of type Nullable<DateTime>, and put it into the Shared/EditorTemplates view folder.
Use jQuery and jQueryUI to put an HTML textbox that is styled as a date/time picker into the partial view.
Decorate the property on your model with the [DataType(DataType.DateTime)] attribute
Use Html.EditorFor(model => model.WhateverProperty)
Fortunately, date/time pickers are probably the most popular custom MVC3 editor, so there are plenty of examples to pick from; the code from this question works fine, just make sure to note the suggestion in the answer and replace this line in the partial view:
#inherits System.Web.Mvc.WebViewPage<System.DateTime>
with this:
#model System.DateTime?
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.