Populating a dropdownlist from a value type - asp.net-mvc-3

This obviously is pretty basic question but I haven't found my way around this: I'm trying to create a dropdown list for an integer property of my Model, so I can populate the dropdown with a default list of values.
My controller looks like this:
ViewBag.MyListOfOptions = new SelectList(new int[] { 5, 15, 25, 50 });
And my view looks like this:
#Html.DropDownListFor(model => model.MyIntField, new SelectList(ViewBag.MyListOfOptions , [dataValueField], [dataTextField]))
Most examples I've found dataValueField and dataTextField are the properties that should be used in creating the dropdown, but I haven't found a way on how to use DropDownListFor with value types

Because you created the SelectList from MyListOfOptions which is already a SelectList you can use "Text" and "Value"
#Html.DropDownListFor(model => model.MyIntField,
new SelectList(ViewBag.MyListOfOptions , "Value", "Text"))
But you don't need to wrap again an SelectList, so this will also work:
#Html.DropDownListFor(model => model.MyIntField,
(IEnumerable<SelectListItem>)ViewBag.MyListOfOptions)

One easy way to get around this is to take this approach using a ViewModel:
dropdownlist set selected value in MVC3 Razor
MVC 3 Layout Page, Razor Template, and DropdownList

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

mvc3 dropdownlist reload and set value

In Edit view:
I am passing ViewBag list for the ddl
Controller:
ViewBag.CountryList = new SelectList(db.Country, "CountryCode", "Desc");
in edit view:
How do I assign the viewbag to the ddl and set the value that is coming from the model
#Html.EditorFor(model => model.CountryCode) <- contains the Desc Value, currently just shows in a textbox!
thx!
use #Html.DropDownListFor. If you read the parameters that C# specifies you need, its self explanitory. The fact you have the selectList in the viewbag already means you've nearly done it all yourself already.
#Html.DropDownListFor(model => model.CountryCode, ViewBag.CountryList);
If that doesnt set the correct value for any reason, you can also use
#Html.DropDownList("CountryCode", ViewBag.CountryList, new { #value = #Model.CountryCode });

Assign default values while creating new Item

This question about Telerik MVC Grid.
I have two Grids with Master->Details relationship. These to grids are loaded using Ajax Binding. I want to create new Item in Details grid and pass ProductId field value from Master grid.
I have added property below but do not know how to get ProductId from Master grid. I have tried to pass value using ViewBag on Detail child loading it it seems ViewBag is not assigned then Ajax call is performed. Maybe someone know how to solve this problem?
Editable(editing => editing.DefaultDataItem(new UserViewModel { ProductId = ?????? })
When you have Master Grid and Detail Grid,
and you want to create record in the Detail Grid ,
You should add JavaScript logic which uses the OnSave event of the Detail Grid to pass additional value to the server (it should be the selected record in the Master Grid).
Check the documentation there are examples.
Have you tried using client side template for this?
Editable(editing => editing.DefaultDataItem(new UserViewModel { ProductId = <#= ProductId #> })
If you're using Ajax binding, you could also pass the parent's ID on insert:
dataBinding.Ajax().Insert("_Insert", "SubItem", new { productId= "<#= ProductId #>" }));
Don't forget to set your DataKey of the parent grid
.DataKeys(keys => keys.Add(c => c.Id))

MVC3 DropDownListFor Model is null on PostBack

I am using a DropDownListFor like this:
#Html.DropDownListFor(model => model.SelectedOrganisationValue, new SelectList(Model.OrganisationList, "Value", "Text"))
And I am also using:
[Required]
As Attribute in the View.
So when I PostBack the View to the Server and the Required Attribute will fail, the View is showed again, but then Model is null. So I will get a NullReferenceException in Model.OrganisationList.
That is the default behaviour. As you know ,MVC does not rely on ViewState, It can not keep the content inside the drop down across Postbacks (generic term). You need to repopulate it again in the ActionMethod.

ASP.Net MVC 3 EditorTemplate for DateTime Fields Error

This code was converted from some ASP.Net MVC 2 code in this tutorial:
MVC 2 Editor Template with DateTime
It is a custom EditorTemplate for DateTime fields stored as 'EditorTemplates/DateTime.cshtml'.
#Model DateTime?
#Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { #class = "datePicker" })
However I get the following error when using #Html.EditorFor(model => model.NewAbsence.StartDate):
CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
I've seen some similar posts on here which mention casting the parameter of the EditorFor method, however I cannot seem to get this to work in my example.
Could someone please point out what I will need to change in my code. Thanks.
Actually it's #model with lowercase m:
#model DateTime?
^
instead of:
#Model DateTime?
So to sort of summarize what people are saying, and make it a bit more generic. If your view is declaring that it accepts dynamic models:
#model dynamic
Then things like extension methods will not be able to infer the types of arguments passed to them. Here are two examples (using Razor because it's awesome):
#Html.TextBox("myTextBoxName", Model.MyTextBoxValue)
#Html.DropDownList("myDropDownName", Model.MySelectList))
In these cases, the engine doesn't know what types Model.MyTextBoxValue or Model.MySelectList are, therefore it can't figure out what overloads of the extension methods to compile. So you just help it along with some strong typing:
#Html.TextBox("myTextBoxName", (string)Model.MyTextBoxValue)
#Html.DropDownList("myDropDownName", (SelectList)Model.MySelectList))
By the way, just to stop people from potentially pulling out their hair, that SelectList has to be properly instantiated with something like:
var items = List<SelectListItem>();
...
new SelectList(items, "Value", "Text");
As a temporary work around I am using:
<div class="editor-field date-field">
#Html.EditorFor(model => model.NewAbsence.StartDate)
#Html.ValidationMessageFor(model => model.NewAbsence.StartDate)
</div>
Then using the jQuery selector:
$(".date-field > input").datepicker({
showOn: "button",
buttonImage: "*pathtoimage*"
});
To apply the date picker to the input tags within the 'date-field' div. However this still doesn't format the date value how I want it to display initially, and cuts out the editor template entirely.
The error message comes from your textbox statement. In a template, this becomes a dynamic expression, and .Net doesn't know how to type the Model properties.
#Html.TextBox("", (string)(Model==null ? Model.Value.ToShortDateString() : string.Empty), new { style = "width: 10em;", #class="datefield" })
Explicitly cast your date value as string, and the dynamic expression has the information it needs. I also had a problem with the .HasValue property, but that wasn't the point of your question.

Resources