Bind the Kendo DropDownListFor - kendo-ui

The kendo dropdownlistfor shows the accurate undefined number of record in dropdown, but it do not show the Item Name. Please help in this regards, Thanks
**Controller**
var cdd = db.Items.Select(x => new
{
x.ItemID,
x.ItemName
}).ToList();
var viewmodel= new Accounting.DAL.Item();
var selec = new SelectList(cdd, "ItemID", "ItemName");
viewmodel.ItemsDrop = selec;
return View(viewmodel);
**Model**
public SelectList ItemsDrop { get; set; }
**View**
#(Html.Kendo()
.DropDownListFor(m => m.ItemName)
.Name("ItemName")
.DataTextField("ItemName")
.DataValueField("ItemID")
.BindTo(Model.ItemsDrop)
)

You're passing a select list to the view so your dropdownlist should look like this:
#(Html.Kendo()
.DropDownListFor(m => m.ItemName)
.Name("ItemName")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.ItemsDrop)
)
If you're controller was just passing a Json result like this:
return Json(cdd.Select( p => new {ItemName = p.ItemName, ItemID = p.ItemID}), JsonRequestBehavior.AllowGet);
then how you had your dropdownlistfor() would be fine as is.

Related

KendoUI for ASPMVC TreeView: display the Json response on behalf of the Tree

I am trying to display a tree of categories with remote data binding.
here is the Controller method:
public JsonResult KendoTree(Guid? id)
{
var categoriesBO = _categoryManager.GetAllCategory().
Where(c=> id==null ? c.ParentId==null : c.ParentId == id).
Select(c=> new
{
id = c.Id,
Name = c.Name,
hasChildren = c.CategoryChilds.Any()
});
return Json(categoriesBO, JsonRequestBehavior.AllowGet);
}
here is the cshtml file
#{
ViewBag.Title = "KendoTree";
}
<h2>KendoTree</h2>
#Html.Kendo().TreeView().Name("Categories").DataSource(dataSource => dataSource
.Read(read => read.Action("KendoTree", "CategoryManagement")
)).DataTextField("Name")
The browser display the Json result(an array) on behalf of the tree.
Am I missing something?
I got it: I have to have a Controller action that returns a view then call the kendo Html helper from inside the related view.

DropDown List in Client Detail Template - Kendo grid

I'm trying to add dropdownlist in client template, but somehow not able, could someone please help me on this?
columns.Bound(o => o.ImportFunctionText).ClientTemplate("# if (ImportFunction == 0) { # Account # } else if (ImportFunction == 1) { # Row # } #")
.EditorTemplateName("DropDownList")
.EditorViewData(new
{
Id = "ImportFunction",
Data = ViewBag.dropDownList,
FieldName = "value:ImportFunction"
})
.Width(210)
.Title("Function");
Thanks.
in order to make use of editor templates you have to store your editor template within the folder ~/Views/Shared/EditorTemplates/tmp_dropdown_attribute.cshtml as a partial view.
according to the telerik asp net mvc docs your should the template look like the following:
#(Html.Kendo().DropDownList()
.Name("Employee") // Name of the widget should be the same as the name of the property
.DataValueField("EmployeeID") // The value of the dropdown is taken from the EmployeeID property
.DataTextField("EmployeeName") // The text of the items is taken from the EmployeeName property
.BindTo((System.Collections.IEnumerable)ViewData["employees"]) // A list of all employees which is populated in the controller
)
and your controller should bind the viewdata container within the controller method which generates the view like that:
public ActionResult Index()
{
ViewData["employees"] = new NorthwindDataContext()
.Employees
.Select(e => new Employee
{
EmployeeID = e.EmployeeID,
EmployeeName = e.FirstName + " " + e.LastName
})
.OrderBy(e => e.EmployeeName);
return View();
}
for further reading please refer to the docs which can be found here:
http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/grid/templating/editor-templates

how to validate telerik mvc grid using remote attribute in data annotations?

I want to check if username already exists in database using telerik mvc grid (batch edit). But The problem is in order to validate it, I need to pass applconst_id as a parameter in CheckDuplicateType function. But it always return "undefined", I don't know how to get the right value.
this is my model class:
public class masterTypeCont
{
[Key]
public Int32 applconst_id { get; set; }
[Required(ErrorMessage = "This field needs a value!")]
[Remote("CheckDuplicateType",
"Type",
AdditionalFields = "applconst_id",
ErrorMessage = "Code already exists.")]
public String note1 { get; set; }
}
and this is my controller:
[HttpGet]
public virtual JsonResult CheckDuplicateType(masterTypeCont tipe, String applconst_id)
{
Int32 intID = Convert.ToInt32(applconst_id);
return Json(typeEnt.ValidateCustomer(intID, tipe.note1), JsonRequestBehavior.AllowGet);
}
And this is ValidateCustomer function:
public bool ValidateCustomer(Int32 id, String nama) {
Int32 x = db.appl_const.Where(a =>
a.group_id == "CH_COMP_CODE" &&
a.note1.Trim() == nama.Trim() &&
a.applconst_id != id).Count();
Boolean res = x == 0 ? true : false;
return res;
}
This is my view:
#{
ViewBag.Title = "Type List";
Layout = "../Shared/_Layout.cshtml";
}
<div class="direct-content">
#using (Html.BeginForm())
{
#(Html.Telerik().Grid<ComplaintHandling.Models.masterTypeCont>()
.Name("TypeGrid")
.Localizable("id-ID")
.ToolBar(commands =>
{
commands.Insert();
commands.SubmitChanges();
})
.DataKeys(keys => keys
.Add(o => o.applconst_id)
.RouteKey("applconst_id"))
.DataBinding(dataBinding =>
{
dataBinding.Ajax()
.Select("_SelectAllType", "Type")
.Update("_SaveBatchType", "Type");
})
.Columns(columns =>
{
columns.Bound(o => o.applconst_id).Hidden();
columns.Bound(o => o.note1).Title("Name");
columns.Command(commands =>
{
commands.Delete().ButtonType(GridButtonType.Text);
}).Title("Command");
})
.ClientEvents(events => events
.OnEdit("OnEditGrid")
)
.Editable(editing => editing.Mode(GridEditMode.InCell))
.Selectable()
.Pageable(pager => pager.PageSize(15))
.Filterable()
.Sortable()
.Scrollable(x => x.Height("450px"))
.KeyboardNavigation()
.Resizable(x => x.Columns(true))
)
<input type="hidden" name="applconst_id" id="applconst_id" value="1">
}
</div>
I write hidden input there to contains the applconst_id, but still it value doesn't passed to controller.
Sorry for my bad english.
Any help will be deeply appreciated.
Thanks.
Try like this:
[HttpGet]
public virtual ActionResult CheckDuplicateType(masterTypeCont tipe)
{
var result = typeEnt.ValidateCustomer(tipe.applconst_id, tipe.note1);
return Json(result, JsonRequestBehavior.AllowGet);
}
Thanks for the answers before.
After doing some research, I finally found solution for my own problem.
I create a little trick there, maybe this isn't a good way, but at least it can solve my problem.
Basically, I just play with the name attribute of an element so that it value can be passed to controller.
Here, I will explain in detail how I've done this.
First, I changed Grid columns in my View to be like this:
Please concern on applconst_id hidden field. I add client template there.
columns.Bound(o => o.applconst_id).Hidden()
.ClientTemplate("<input class='typeID' name='common_id' value='<#= applconst_id #>'>");
columns.Bound(o => o.note1).Title("Nature of complaint");
Second, I add this code in "onEdit" function:
//this code change ID that is being edited, so that it can be passed to controller
var $inputID = $('.t-grid-edit-cell').prev().find('.typeID');
$inputID.attr('name', 'applconst_id');
//change back ID that is not being edited, so that it's not passed to controller
$('td:not(.t-grid-edit-cell)').prev().find('.typeID').attr('name','common_id');
Third, this is my controller:
[HttpGet]
public JsonResult CheckDuplicateType(String applconst_id, String note1)
{
Int32 IntID = Convert.ToInt32(applconst_id);
return Json(typeEnt.ValidateCustomer(IntID, note1), JsonRequestBehavior.AllowGet);
}
And my "ValidateCustomer" function stay the same.
I hope my solution can help other people who have the same problem with me.
Thanks.
Regards,
L.W.

MVC3 DropDownListFor not populating selectedValue

I feel like I'm taking crazy pills. I have a dropdownlist for a view that reads from our database all of the wine producers we have. I want to set the selectedValue to a particular ID driven by the referring page. I can see it picks up the selectedValue in debug, I see the selected value populated (906 for this example), but it doesn't set the dropdownlist to the correct value when the page is rendered, it always defaults to 1 for the default value. I've tried creating the selectList in razor as opposed to my controller, but nothing works. Any help on this would be appreciated, I'm guessing it is something small.
Controller:
if (User.IsInRole("admin"))
{
if (ID != 0)
{
ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name", ID);
}
else
{
ViewBag.ProducerSelect = new SelectList(db.Producers.OrderBy(p => p.Name), "ProducerID", "Name");
}
}
View:
if (User.IsInRole("producereditor"))
{
<h3>#ViewBag.ProducerName</h3>
}
else
{
<div class="editor-label">
#Html.LabelFor(m => m.Wine.ProducerID, "Producer")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.Wine.ProducerID, ViewBag.ProducerSelect as SelectList)
</div>
}
Tried the below but no success:
ViewBag.ProducerSelect = new SelectList(from p in db.Producers
orderby p.Name
select new { p.ProducerID, p.Name }
, "ProducerID", "Name", ID);
If you want to preselect an item, You set that value to your ProducerId property.
var yourViewModelObj=new YourViewModel;
yourViewModelObj.Wine.ProducerId=906; //or whatever value you want
return View(yourViewModelObj);
Suggestion : For better code readablity/Maintenance, Try to avoid ViewBag / ViewData and use a ViewModel to pass the data.
I would add a Property to my ViewModel to hold the Collection of Producers
public class WineViewModel
{
//Other Existing properties also
public IEnumerable<SelectListItem> Producers{ get; set; }
public string SelectedProducer { get; set; }
}
Then in yout GetAction method, you can set the value like this, If you want to set one select option as the default selected one.
public ActionResult CreateWine()
{
var vm=new WineViewModel();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.Producers= new[]
{
new SelectListItem { Value = "1", Text = "Prodcer A" },
new SelectListItem { Value = "2", Text = "Prodcer B" },
new SelectListItem { Value = "3", Text = "Prodcer C" }
};
//Now let's set the default one's value
vm.SelectedProducer = "2";
return View(vm);
}
And in your Strongly typed View,
#Html.DropDownListFor(x => x.SelectedProducer,
new SelectList(Model.Producers, "Value", "Text"), "Select Producer")
The HTML Markup generated by above code will have the HTML select with the option with value 2 as selected one.
I figured this out. I had ViewModel.wine.ProducerID elsewhere on the page in a hidden field, and that defaults to 1, so I just assigned that to passed in value, and it worked great. I knew it was something like that. Thanks!
User a ViewModel ex WineViewModel
public class WineViewModel
{
public Wine Wine { get; set; }
public SelectList PProducerList { get; set; }
public WineViewModel() { }
public WineViewModel(Wine wine)
{
this.Wine = wine;
}
}
Try the following in your controller
var model = new WineViewModel( selectwine);
model.ProjectTypeList = new SelectList( from p in db.Producers
orderby p.Name
select new { p.ID, p.Name }, "ID", "Name")
notice how I am exclusively declaring which is the ID and which is the Value in my SelectList
Then in your view do
#Html.DropDownListFor(model => model.Wine.ProducerID, Model.ProjectTypeList)

How do you properly create a MultiSelect <select> using the DropdownList helper?

(sorry, there are several item here but none seems to allow me to get this working.)
I want to create a DropDownList which allows multiple selection. I am able to populate the list but I can't get the currently selected values to seem to work.
I have the following in my controller:
ViewBag.PropertyGroups = from g in db.eFinGroups
where g.GroupType.Contents == "P"
select new
{
Key = g.Key,
Value = g.Description,
Selected = true
};
ViewBag.SelectedPropertyGroups = from g in company.Entities
.First().Properties.First().PropertyGroups
select new {
g.eFinGroup.Key,
Value = g.eFinGroup.Description };
In the view I have:
#Html.DropDownListFor(model => model.PropertyGroupsX,
new MultiSelectList(ViewBag.PropertyGroups
, "Key", "Value"
, ViewBag.SelectedPropertyGroups),
new { #class = "chzn-select", data_placeholder = "Choose a Property Group", multiple = "multiple", style = "width:350px;" })
PropertyGroupX is a string[] in the model.
I have tried all types of iterations with the selected properties... passing just the value, just the key, both, etc.
Also, what type is PropertyGroupX supposed to be? Is string array correct? Or should it be a dictionary that contains the current propertygroups? I really am having a hard time finding doc on this.
Someone suggested I should be using ListBoxFor. I have changed to that and still have the same issue. The selected values are not being set as selected when the option tags are rendered. Here is what I have tried:
#Html.ListBoxFor(model => model.PropertyGroups, new MultiSelectList(ViewBag.PropertyGroups, "Key", "Value"))
I have tried the model.PropertyGroups as a collection of string matching the Values, as a collection of Guid matching this IDs and as an anonymous type with both a Key and Value to match the items in the ViewBag. Nothing seems to work.
You don't use DropDownListFor if you want to create a multiselect list. You use the ListBoxFor helper.
View model:
public class MyViewModel
{
public string[] SelectedIds { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
public ActionResult Index()
{
var model = new MyViewModel
{
// preselect the first and the third item given their ids
SelectedIds = new[] { "1", "3" },
// fetch the items from some data source
Items = Enumerable.Range(1, 5).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = "item " + x
})
};
return View(model);
}
View:
#model MyViewModel
#Html.ListBoxFor(x => x.SelectedIds, Model.Items)

Resources