Kendo UI DropDownList - Html Helper (Razor) - Hardcode list options - c#

I'm setting up a project with Kendo Ui for the first time, and I'm trying to create Kendo UI dropdown lists, but am getting:
ArgumentNullException was unhandled by user code.
--Value cannot be null.
My code is:
#(Html.Kendo().DropDownList()
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>()
{
new SelectListItem()
{
Text = "Active",
Value = "1"
},
new SelectListItem()
{
Text = "In-active",
Value = "2"
}
})
.Value("1")
) <-- the error is pointing to here.
Does anyone know what value is missing?
Thanks,

Each KendoUI component must have a name specified.
Add this:
.Name("whatYouWantForHtmlId")

Related

preselect dropdown list razor page

I have the below code that I use to populate my dropdown in my Razor Page
I want to preselect a description - the "Value" of that needs to be set is found in
s.UserEstablishmentId
How can I preselect this on the dropdown
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
You're using linq to create a new SelectListItem for getEstablishments element. When creating each instance of a SelectListItem() you need to determine if Selected should be true or false. Simply replace YourConditionForSelectionHere with a method that returns a bool or syntax that returns a bool, shown below:
#Html.DropDownList("drpEstablishments",
getEstablishments().Select(s => new SelectListItem()
{
Selected = (YourConditionForSelectionHere),
Text = s.Description,
Value = s.EstablishId.ToString()
}),
new
{
#class = "dropdown form-control"
})
in the end something like this worked
Selected= (s.UserEstablishmentId==s.EstablishId)? true:false,

MVC how to change dropdownlist item names

Been googling for a while, but I can't seem to get any closer.
I'm using MVC with an EF Database structure.
I want the dropdownlist items in the View to show up with different names than what they come up with.
Right now, the lambda query returns a list().
I want each item to get a string name depending on their current name. Eventually, the selected field needs to be used in another lambda as the Byte that it was.
Edit
//view
<p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
#Html.DropDownList("vbType", (SelectList)ViewBag.Type, "" , new { onchange = "form.submit();" })
....
//controller
var typeLst = new List<byte>();
var typeQry = from t in db.model1
orderby t.TYPE
select t.TYPE;
typeLst.AddRange(typeQry.Distinct());
ViewBag.vbType = new SelectList(typeLst);
....
Thanks in advance.
You can create a SelectListItem to display in your dropdownlist.
Example:
#Html.DropDownListFor(model => model.YearStartedToPay,
Enumerable.Range(DateTime.Today.Year - 60, 61).OrderByDescending(x => int.Parse(x.ToString())).Select(n => new SelectListItem() { Text = n.ToString(), Value = n.ToString(), Selected = false }).ToList<SelectListItem>(),....)
In this case, I'm creating an Enumerable, that will be your list returned from EF, ordering and selecting as a SelectListItem.
You need to make use of dropdownlist's Value property. Make your list a type of SelectListItem.
Assign Text= [Your Required Text] and Value = [Current Name]

How do I make a select list from a Viewbag item list?

I have a list created from a controller which is passed to a viewbag item:
List<SelectListItem> PTL = new List<SelectListItem>();
List<PT> PTL2 = db.PT.ToList();
foreach (var item in PTL2)
{
PTL.Add(new SelectListItem { Value = item.ID.ToString(), Text = item.Name });
}
ViewBag.PTL2 = PTL2;
Then, in the view, I tried the following from another question here:
#Html.DropDownList("test", new SelectListItem[]{
new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}}
, htmlAttributes: new { #class = "form-control" })
which worked fine, but, if I try to edit it to the following:
#Html.DropDownList("test", ViewBag.PTL2, htmlAttributes: new { #class = "form-control" })
I get various errors.
I have spent hours on this trying different combinations, different castings and more, but, I just don't seem to be making progress.
I have seen so many different errors - the most common one being '
There is no ViewData item of type IEnumerable<SelectListItem> that
has the key “test”'
However, I tried casting and changing the name as per different questions here, but, I just can't seem to get past this.
At this point, I am thinking of just making a manual HTML Drop Down list and a foreach loop for the content, but, this seems a waste.
Does anyone know what I have done wrong?
The second parameter must be a collection of System.Web.Mvc.SelectListItem objects that are used to populate the drop-down list. But, you are using ViewBag property in this case and the type of this is dynamic. So, you must cast it to the collection of the SelectListItem. Otherwise, you will get this error in MVC 4+:
Extension methods cannot be dynamically dispatched
So. as a result just change
ViewBag.PTL2
to
ViewBag.PTL2 as IEnumerable<SelectListItem>.
i hope it is not too late ,this is how i do it with .net core
in your controller ,use below code
public ActionResult ShowCalendar()
{
var programs = new Microsoft.AspNetCore.Mvc.Rendering.SelectList((new Programs().GetAll().ToList(), "ID", "Name")
ViewBag.AllItems = programs;
return View();
}
and in your cshtml file use the below
<select id="ItemID" class="form-control"
asp-items="ViewBag.AllItems">
<option disabled selected>--- #Localizer["PleaseSelect"] ---</option>
</select>
will do the job for you

How to update KendoGrid from combobox

I'm writing a web app in ASP.NET MVC using Kendo UI. I'm visualizing data in a Kendo Grid as follows:
#(Html.Kendo().Grid<MyModel>()
.Name("grid")
.DataSource(dataSource => dataSource // Configure the grid data source
.Ajax() // Specify that ajax binding is used
.Read(read => read.Action("ReadAction", "MyController", new { /*route values*/ }))
)
.Columns(columns =>
{
columns.Bound(n => n.Month).Title("Month").ClientTemplate("<input type='hidden' value='#=Month#' id='hfMonth'/>").Hidden();
columns.AutoGenerate(true);
})
.Pageable()
.Sortable()
Now I need to fire an update of the grid based on the change event of a <select>. How can I do this? I'm trying several possibilities from yesterday, with no success as all.
Without seeing your code for the combobox I would do the following:
View
#(Html.Kendo().ComboBox()
.Name("combo")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Foo", Value = "1"
},
new SelectListItem() {
Text = "Bar", Value = "2"
},
new SelectListItem() {
Text = "Baz", Value = "3"
}
})
.Events(events =>
{
events.Change("onChange");
})
)
JavaScript
function onChange(e) {
var grid = $("#grid").data("kendoGrid");
// if the selected value is not needed
grid.dataSource.read();
// if the selected value is needed use below instead
// changing the route parameter to match yours
var selectedValue = this.Value();
grid.dataSource.read({ id : selectedValue });
}
Update
As per #PierpaoloIlConteParis comments:
I didn't specify directly the parameters in the read.Action method, but instead I used the handler function like in this post telerik.com/forums/… Now when changing the combobox value the action fires with right parameters

Getting Disabled Dropdown values in MVC

I am pretty new to MVC. In my form i have a disabled dropdown control whose value is not getting passed to the Model during submit as it is disabled. I tried using a hidden field like below
#Html.DropDownListFor(model => model.DepartmentID, new List<SelectListItem> { new SelectListItem { Text = "Item 1", Value = "1" }, new SelectListItem { Text = "Item 2", Value = "2", Selected = true } })
#Html.HiddenFor(model => model.DepartmentID)
Both of the above statement produce controls having the same id so i was not sure can i get the value of the dropdown in the hidden field.
I could use a different id while creating the hidden variable and assign the dropdown value it it using jquery.
I just want to know if i can achieve the same using the Hidden field having the same id as shown in the above code ??
Form Fields are not submitted by ID, they're submitted by name. It's ok for there to be two controls with the same name. However, it's invalid HTML to have two elements with the same id.
You can set a different ID but keep the same name like this:
#Html.HiddenFor(x => x.DepartmentID, new { id="DepartmentID2" })

Categories

Resources