Reputation: 23
I have an ASP.NET MVC application and I use Kendo UI for a dropdown list with HTML Helpers. When I want to set a default value for a View that is for editing the data .Value() doesn't work. Here's my code for the View:
@(Html.Kendo().DropDownListFor(m => m.UserName)
.Name("userName")
.DataTextField("UserName")
.DataValueField("UserId")
.BindTo(Model.Mechanics)
.Value(Model.UserName)
)
And this is the code for the Action that gets the data:
public ActionResult EditServiceCart(int id)
{
var servCart = db.ServiceCarts.Where(x => x.CarId == id).SingleOrDefault();
var mechanics = db.UserProfiles.Select(m => new MechanicsViewModel
{
UserId = m.UserId,
UserName = m.UserName
}).ToList();
var model = new EditServiceCartViewModel
{
ServiceCartId = servCart.ServiceCartId,
Mechanics = mechanics,
UserName = servCart.UserName
};
return View(model);
}
If I use a hardcoded binding (e.g .BindTo(new string[] {"Mechanic 1", "Mechanic 2", "Mechanic 3"})) .Value() works fine, but with my it's not. I saw that in the HTML the value that is displayed for the dropdown is in and .Value method doesn't change it. It changed the value for the , which really is what I want but it's no matter because it's not displayed.
Upvotes: 1
Views: 14873
Reputation: 1167
Your code should be
@(Html.Kendo().DropDownListFor(m => m.UserName)
.Name("userName")
.DataTextField("UserName")
.DataValueField("UserId")
.BindTo(Model.Mechanics)
.Value(Model.UserId) // Model.UserId(or something like that) NOT Model.UserName
)
Because you told Kendo that : "I'm going to use UserId
as DropdownList Value" .
When you pass Model.UserName to .Value() method, Kendo UI can't find that value
Upvotes: 3