10

I'm working with KendoUI MVC in MVC3.

I managed to get a dropdown in a grid column. But I have no clue on how to set the selected value, and when I save it doesn't save my selected value.

The grid

@using Perseus.Areas.Communication.Models
@using Perseus.Common.BusinessEntities;


<div class="gridWrapper">
    @(Html.Kendo().Grid<CommunicationModel>()
        .Name("grid")
        .Columns(colums =>
        {
            colums.Bound(o => o.communication_type_id)
                .EditorTemplateName("_communicationDropDown")
                .ClientTemplate("#: communication_type #")
                .Title("Type")
                .Width(180);
            colums.Bound(o => o.sequence).Width(180);
            colums.Bound(o => o.remarks);
            colums.Command(command => command.Edit()).Width(50);
        })
        .Pageable()
        .Sortable()
        .Filterable()
        .Groupable()
        .Editable(edit => edit.Mode(GridEditMode.InLine))
        .DataSource(dataSource => dataSource
            .Ajax()
            .ServerOperation(false)
            .Model(model => model.Id(o => o.communication_id))
                .Read(read => read.Action("AjaxBinding", "Communication", new { id = @ViewBag.addressId }))
                .Update(update => update.Action("Update", "Communication"))
            .Sort(sort => { sort.Add(o => o.sequence).Ascending(); })
            .PageSize(20)
        )
    )
</div>

The EditorTemplate "_communicationDropDown

@model Perseus.Areas.Communication.Models.CommunicationModel


@(Html.Kendo().DropDownListFor(c => c.communication_type_id)
        .Name("DropDownListCommunication")
            .DataTextField("description1")
            .DataValueField("communication_type_id")
            .BindTo(ViewBag.CommunicationTypes))
Kristof Claes
  • 10,797
  • 3
  • 30
  • 42
bjornruysen
  • 850
  • 1
  • 6
  • 15
  • 1
    Did you get any solution? I have same problem. I am able to show text in drop-down list, How can I set value. – Systematix Infotech Jul 25 '14 at 11:04
  • Seems the problem is solved, could you please clarify what is the ''communication_type' field? in your clientTemplate? – Gyuzal Feb 26 '15 at 10:12
  • Where you are defining `.ClientTemplate("#: communication_type #")`? Can you please post your controller of the entire grid. –  Oct 21 '15 at 14:30

1 Answers1

19

I think this is an important one to point out is that the DropDownList name should match the column name attribute. The html attribute name="", not the heading of the column. The name attributes must match for this to work, since you are substituting the default editor control with another control coming from an editor template to take its place during the edit operation. If the names do not match when the DOM is serialized back into the model for the update operation, the value from the editor template control will be ignored. By default it is the property variable name that appears in the model class, unless overriden in the mark up.

(Answer edited to include the insert record operation).

Here is a working example:

Model Class:

public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
}

View:

@(Html.Kendo().Grid<Employee>()
     .Name("Grid")
     .Columns(columns =>
     {
         columns.Bound(p => p.Name).Width(50);
         columns.Bound(p => p.Department).Width(50).EditorTemplateName("DepartmentDropDownList");
         columns.Command(command => command.Edit()).Width(50);
     })
     .ToolBar(commands => commands.Create())
     .Editable(editable => editable.Mode(GridEditMode.InLine))
     .DataSource(dataSource => dataSource
         .Ajax() 
         .Model(model => model.Id(p => p.EmployeeId))
         .Read(read => read.Action("GetEmployees", "Home")) 
         .Update(update => update.Action("UpdateEmployees", "Home"))
         .Create(create => create.Action("CreateEmployee", "Home"))
     )
)

Partial view editor template, file name "DepartmentDropDownList", located in the EditorTemplates folder that is specific to this view. ie. Home\Views\EditorTemplates\DepartmentDropDownList.cshtml

@model string

@(Html.Kendo().DropDownList()
    .Name("Department")  //Important, must match the column's name
    .Value(Model)
    .SelectedIndex(0)
    .BindTo(new string[] { "IT", "Sales", "Finance" }))  //Static list of departments, can bind this to anything else. ie. the contents in the ViewBag

Controller for the Read operation:

public ActionResult GetEmployees([DataSourceRequest]DataSourceRequest request)
{
    List<Employee> list = new List<Employee>();
    Employee employee = new Employee() { EmployeeId = 1, Name = "John Smith", Department = "Sales" };
    list.Add(employee);
    employee = new Employee() { EmployeeId = 2, Name = "Ted Teller", Department = "Finance" };
    list.Add(employee);

    return Json(list.ToDataSourceResult(request));
}

Controller for the Update operation:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateEmployees([DataSourceRequest] DataSourceRequest request, Employee employee)
{
    return Json(new[] { employee }.ToDataSourceResult(request, ModelState));
}

Controller for the Create operation:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CreateEmployee([DataSourceRequest] DataSourceRequest request, Employee employee)
{
    employee.EmployeeId = (new Random()).Next(1000);  
    return Json(new[] { employee }.ToDataSourceResult(request, ModelState));
}
Igorrious
  • 1,608
  • 16
  • 15
  • 1
    *Facepalm* I can't believe I didn't think of that. Changing the name of the dropdown to the matching column name works like a charm! Thank you very much! – bjornruysen Jun 21 '12 at 07:09
  • Cant find any good examples of EditorTemplateName. Can you clarify what is "DepartmentDropDownList"? a partial view or ascx, and in what folder should i place it? – Syed Mehroz Alam Jun 21 '12 at 12:38
  • 1
    Figured out. Need to place it in the EditorTemplates folder for the current controller's (or common) View folder. – Syed Mehroz Alam Jun 21 '12 at 13:59
  • @Igorrious For one strange reason or another it doesn't work when I try to 'create'. Updating works fine, but at creation the id isn't posted.. – bjornruysen Jun 21 '12 at 14:23
  • @SyedMehrozAlam Yes, you got it. I updated the answer to include your feedback. – Igorrious Jun 21 '12 at 16:43
  • @bjornruysen Answer has been updated to include the insertion of a new record. The id is something you need to set, if your id is calculated on the database side like an identity, let the repository insert your record and then do a select to retrieve the id. Update the object, return it to the controller and have it update the grid. – Igorrious Jun 21 '12 at 17:08
  • What if your model has a complex object and that value needs to be stored in a child property of that complex object? – nav Nov 25 '13 at 19:45
  • Ugh, I had the same issue as you. So annoying when you forget to name things the same thing. – IyaTaisho Feb 20 '14 at 13:45
  • Wow you saved my life sir. Thank you @Igorrious – Nerd in Training Jan 29 '19 at 14:11