I am trying to use my viewModel to validate a form both client side and server side. I have got all the validation working except for my Kendo Combobox. I have bound the model to the multiselect but I don't know how to distinguish between the list and the selected value.
Combobox:
@(Html.Kendo().ComboBox()
.Name("roleRequest_UnavailableRoles")
.BindTo(new SelectList(Model.roleRequest.UnavailableRoles, "Value", "Text"))
.HtmlAttributes(new { name="addRoleName", style = "width:250px", required = true, roleValidationMessage = "foo" })
.Value(Model.roleRequest.roleName)
.DataTextField("Text")
.DataValueField("Value")
.Filter(FilterType.StartsWith)
.Placeholder("Select Role...")
.AutoBind(false)
.Suggest(true)
)
View Model:
[Required]
public string roleName { get; set; }
[Required]
public string usersName { get; set; }
[Required]
public string application { get; set; }
[Required]
public string reasons { get; set; }
public virtual IEnumerable<SelectListItem> UnavailableRoles
{
get
{
var unavailableList = new List<Role>();
unavailableList = RoleHelper.GetUnavailableRoles(usersName, application);
var unavailableRolesList = (unavailableList.Distinct());
var UnavailableRoles = new List<SelectListItem>();
foreach (var role in unavailableRolesList)
{
UnavailableRoles.Add(new SelectListItem
{
Value = role.RoleID.ToString(),
Text = role.RoleName
});
}
return new SelectList(UnavailableRoles, "Value", "Text");
}
}
Controller: [HttpPost] public ContentResult RoleRequest(AddRoleRequestViewModel viewModel) { if (ModelState.IsValid) { return Content("1"); } return Content(""); }
The code above does compile but I can't get the controller to return invalid if no item is selected in the combobox. can anyone explain how to fix this?
Any help would be greatly appreciated.
If you use Html.Kendo().ComboBoxFor()
you can bind it to a model property similar to this:
@(Html.Kendo().ComboBoxFor(m => m.UnavailableRoles)
.Name("roleRequest_UnavailableRoles")
.BindTo(new SelectList(Model.roleRequest.UnavailableRoles, "Value", "Text"))
.HtmlAttributes(new { name="addRoleName", style = "width:250px", required = true, roleValidationMessage = "foo" })
.Value(Model.roleRequest.roleName)
.DataTextField("Text")
.DataValueField("Value")
.Filter(FilterType.StartsWith)
.Placeholder("Select Role...")
.AutoBind(false)
.Suggest(true)
)
Note that when doing this, you don't need the Name()
or Value()
properties because they will be handled when using the ComboBoxFor()
This will take care of binding the control to the model and also allow you to use the validation.
Also, one thing I missed in your model: You'll want another property for the actual values (besides just the options). I would do something like this:
public List<Guid> RoleIds { get; set; } // or List<int> if you're using integers
and then change your ComboBoxFor to ComboBoxFor(x => x.RoleIds)