Kendo ui mvc dropdownlistfor with boolean type value using Entity Framework - kendo-ui

#Html.Kendo().DropDownListFor(model => model.Is_Active)
//instead of #Html.EditorFor(model => model.Is_Active)"
I am using entity crud operation and Is_Active is a boolean type value. On generating edit view it shows dropdown list which code is
#Html.EditorFor(model => model.Is_Active)
and I want to change it in kendo ui using
#Html.Kendo().DropDownListFor(model => model.Is_Active)
but it shows blank dropdown list - please provide a response

You need to specify the DataSource for the DropDownList otherwise there is no list of items in it. You use the .BindTo() for that.
Html.EditorFor() works because the internal implementation for a boolean creates the True/False item list for you.
When you explicitly define a DropDownList you need to provide both the value AND the list of potential values using .BindTo(), i.e.
#{
var boolDataSource = new List<SelectListItem>()
{
new SelectListItem() { Text = "True", Value = "True" },
new SelectListItem() { Text = "False", Value = "False" }
};
// Or however/wherever you want to define the list of items that the DropDownList uses.
}
#Html.Kendo().DropDownListFor(model => model.Is_Active).BindTo(boolDataSource)

Related

Kendo UI DropDownListFor Set SelectedValue

I'm working with Kendo UI on an MVC application. We have a grid and when the user opens the row for editing we have a dropDownList that holds company names. I'm trying to get the DDL to default to the company name that's pertinent to the row.
Here's the column code:
columns.Bound(e => e.company_business_name).Width(220).Title("Company")
.EditorTemplateName("CompanyName");
and here's the editorTemplate code:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.BindTo((System.Collections.IEnumerable)ViewData["Companies"])
)
and the method that fills the DDL:
private void PopulateCompanies()
{
var companyList = new List<SelectListItem>();
if (!string.IsNullOrEmpty(Session["Companies"] as string))
{
companyList = (List<SelectListItem>)Session["Companies"];
}
else
{
companyList = new DataAccess().GetCompanies(CurrentSettings.getUser().userId);
CacheCompanies(companyList);
}
ViewData["Companies"] = companyList;
}
EDIT:
Updated the code. The DDL still populates but I'm still not getting the selected value when I click "edit" on the grid row. Feel like I'm close here, help!
The problem is that your Editor Template's model is your entire model, not the company_business_name property (Very bad name for a property, by the way. You need to follow the standard naming conventions).
You don't even need to fill the drop down list.
Your Editor Template should be something like this:
#model string
#(Html.Kendo().DropDownListFor(m => m)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(x =>
x.Read(read => read.Action("GetCompanies", "AddEntry"))
)
)

Kendo UI ASP.Net MVC ForeignKey column DataSource in InCell Edit mode

I have Kendo Grid and a ForeignKey column on a page. ForeignKey column is populated using ViewData as described below.
column.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName");
The Grid is editable in batch(InCell) mode as show below...
.Editable(editable => editable.Mode(GridEditMode.InCell)
I want to modify collection of ProductID column in the grid after page is loaded based on value selected on other drop-down defined outside of the Grid.
How can I achieve that? Can I do it using jQuery?
Similar example I found here...
http://www.telerik.com/community/forums/aspnet-mvc/grid/cascading-dropdowns-in-grid-edit---foreignkey-columns.aspx
Thanks.
I figured out how to filter the Product drop-down using an EditorTemplate for the foreign key column.
Here is my column definition for the Product.
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName").EditorTemplateName("ProductIDEditor");
Here is the editor template for Product, ProductIDEditor.cshtml
#using Kendo.Mvc.UI
#(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.OptionLabel("Select a value...")
.DataTextField("ProdName")
.DataValueField("ID")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("FilterProducts", "Home").Data("filterProducts"))
.ServerFiltering(true);
})
)
#Html.ValidationMessageFor(m => m)
In my main VIEW Index.cshtml, I added filterProducts JavaScript handler, that passes JSON object for productID to controller.
function filterChargeTypes()
{
return {
productID: $("#ProductID").val()
};
}
Here is the controller that listens to filtering event...
public ActionResult FilterProducts(string productID)
{
// do your filtereing based on productID.
}
FilterProducts will be called every time when user hits the drop-down to get filtered value.
You don't need the Editor Template. It will bind to a dropdown without it. You can use this, like you had, just minus the template:
c.ForeignKey(x => x.ProductID, (List<Product>)ViewData["products"], "ID", "ProdName")
or
c.ForeignKey(x => x.ProductID, (System.Collections.IEnumerable)ViewData["products"], dataFieldValue: "ID", dataFieldText: "ProdName")
And for filtering, you can just invoke .Filterable() on the grid.

Loop through IEnumerable in #Html.DropDownListFor (MVC3)

I have a collection of models that I am passing to my view and I want to display each model.property in the dropdownlist. The problem is there is a bug in my code where it shows two duplicate items.
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#Html.Label("BRAD Module:")&nbsp
#Html.DropDownListFor(model => model.FirstOrDefault().module_name, Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name }), new { id = "ddlSelectedBrad", onchange = "chkSelection()" })
I am currently using FirstOrDefault() to access the module name for each model in my collection of models. But by doing this I have a duplicate value.
See screenshots below:
MARKET:LEISURE is showing twice
Intelligence is showing twice. If I change this dropdown value and return to this screen it will show two duplicate values.
Summary
Does anyone know a better way of writing the LINQ query?
Thanks.
Instead of
Model.Select(x => new SelectListItem { Text = x.module_name, Value = x.module_name })
Try
Model.GroupBy(x => x.module_name).Select(x => new SelectListItem { Text = x.First().module_name, Value = x.First().module_name })
This should filter the duplicate records.

dropdownlist for following

var dropdown = (from role in db.aspnet_Users
where role.aspnet_Roles.Any(a => a.RoleName == "supervisor")
select new
{
text = role.UserName,
value = role.UserId
}).ToList();
code to generate dropdown list having dropdown.text as DropdownList item/text and dropdown.value as DropdownList value
This code Present in my view.cshtml
using razor:
#Html.DropDownList("name",
new SelectList( dropdown ,
"value",
"text" ) )
where dropdown is your variable
Also considering moving your code to the controller and passing the variable through viewbag (ie: ViewBag.dropdownitems = dropdown)

MVC DropDownListFor() Selected Item is not Selected / Required Validation not run

I am having trouble getting my DropDownList to set the selected item to the value from the model.
The field in the model is just a string for the Title of the users name (Mr, Miss etc..) Below is my code so far.
<td>
#{ var list = new List<SelectListItem>(new[] {
new SelectListItem{ Selected = string.IsNullOrEmpty(Model.Title), Text="",Value=""},
new SelectListItem{ Selected = Model.Title.Equals("Mr"), Text="Mr",Value="Mr"},
new SelectListItem{ Selected = Model.Title.Equals("Mrs"), Text="Mrs",Value="Mrs"},
new SelectListItem{ Selected = Model.Title.Equals("Miss"), Text="Miss",Value="Miss"},
new SelectListItem{Selected = Model.Title.Equals("Ms"), Text="Ms",Value="Ms"}
});
}
#Html.DropDownListFor(m=>m.Title, list)
</td>
I had this problem with MVC 3 and it turned out that I had set ViewBag.Title on my View (using it for the page title). As soon as I changed it to ViewBag.PageTitle, the dropdownlist code started working : #Html.DropDownListFor(model => model.Title, Model.MySelectList)
The reason for this is that in MVC 2/3, any ViewBag / ViewData properties with the same name as those in the Model object get used in preference in DropDownListFor(), so you need to rename them to make sure they don't conflict. Because that seems really flaky, I just stopped using ViewBag entirely and now rely only on the View Model for passing stuff into the View.
The reason this problem is so prevalent is that ViewBag.Title is used in many introductory tutorials and demo code to set the HTML title element, and so inevitably gets adopted as a "best-practice" approach. However, Title is a natural Model property name for use in dropdowns on a "User Details" view.
So it turns out that the only reason it doesn't work is because my field name is Title, I changed it to Prefix and my exact code works. Way too much time spent finding that out...
Here is working code.
<td>
#{ var list = new List<SelectListItem>(new[] {
new SelectListItem {
Selected = string.IsNullOrEmpty(Model.Prefix),
Text="",
Value=""
},
new SelectListItem {
Selected = Model.Prefix.Equals("Mr"),
Text="Mr",
Value="Mr"
},
new SelectListItem {
Selected = Model.Prefix.Equals("Mrs"),
Text="Mrs",
Value="Mrs"
},
new SelectListItem {
Selected = Model.Prefix.Equals("Miss"),
Text="Miss",
Value="Miss"
},
new SelectListItem {
Selected = Model.Prefix.Equals("Ms"),
Text="Ms",
Value="Ms"
}
});
}
#Html.DropDownListFor(m => m.Prefix, list)
</td>

Resources