I'm having quite a bit of difficulty displaying selected/default values in a DropDownList. I created an appropriate ViewModel:
namespace KendoVolunteerApp.Models.ViewModels
{
public class OrganizationViewModel
{
public int OrganizationId { get; set; }
public string Name { get; set; }
}
}
and Controller
using KendoVolunteerApp.Models;
using KendoVolunteerApp.Models.ViewModels;
using System.Linq;
using System.Web.Mvc;
namespace KendoVolunteerApp.Controllers
{
public class DropDownListController : Controller
{
private VolunteersDbContext db = new VolunteersDbContext();
// GET: DropDownList
public ActionResult DropDownList()
{
return View();
}
public JsonResult DropDownList_GetOrganizations()
{
var organizations = db.Organizations.Select(organization => new OrganizationViewModel
{
OrganizationId = organization.OrganizationId,
Name = organization.Name
});
//if (!string.IsNullOrEmpty(text))
//{
// organizations = organizations.Where(p => p.Name.Contains(text));
//}
return Json(organizations, JsonRequestBehavior.AllowGet);
}
}
}
The DropDownList is part of a custom editor template.
. . .
<div>
<div class="form-group col-md-4">
<div class="k-label-top">
@Html.LabelFor(model => model.Organization)
</div>
<div class="k-dropdown">
@(Html.Kendo().DropDownListFor(model => model.Organization)
.Name("organizations")
.Filter("contains")
.DataTextField("Name")
.DataValueField("OrganizationId")
.OptionLabel("Select organization....")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("DropDownList_GetOrganizations", "DropDownList");
}).ServerFiltering(true);
})
.HtmlAttributes(new { style = "width: 300px" }) )
</div>
</div>
. . .
The DropDownList is being populated, as it should. My issue is that I need to have a particular organization selected by default, in those scenarios where a volunteer is part of an organization. Organization is not required field, as not all volunteers belong to an organization. There is no relationship between the two tables. The name of the organization is stored in the organization field of the volunteer table.
It's setting this selected/default value that is giving me problems.
I've been through various examples, but could not find anything that met my needs. Any help or suggestions would be very much appreciated.
Thank You