How to Pass Kendo DropDownList DataTextField value to Controller

2.1k views Asked by At

I have a Kendo DropDownList on the View and I want to pass its DataTextField value to the Controller and then pass and them on the labels in another View. Although I can pass DataValueField values to the Controller, I cannot pass DataTextField values. I tried to apply different scenarios but I could not. Any idea? On the other hand, if it is not possible, should the DataTextField values be populated again on the Controller and return to the other View?

View:

@model IssueViewModel

...
@Html.LabelFor(m => m.ProjectID)
@(Html.Kendo().DropDownList()
    .Name("ProjectID")
    .DataTextField("ProjectName")
    .DataValueField("ProjectId")
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("GetProjects", "Issue");
        });
    })
)

Controller:

public JsonResult GetProjects()
{
    var projects = repository.Projects;
    return Json(projects.Select(m => new { ProjectId = m.ID, ProjectName = m.Description }), JsonRequestBehavior.AllowGet);
}


/* I want to pass the DataTextField values to this 
method and return them to the CreateManagement view */
public ActionResult Create(IssueViewModel issueViewModel)
{
    return RedirectToAction("CreateManagement", issueViewModel);
}
1

There are 1 answers

3
Amirhossein Mehrvarzi On BEST ANSWER

Change your controller to this:

public JsonResult GetProjects()
{
    var projects = repository.Projects;
    return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description, ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);
}

Since the DropDownList uses DataTextField for the user and uses DataValueField for the server communications, so you have to use DataTextField value for both. Then you can use it for the next operations.

Edit: if you need both values on the controller, change JsonResult method to :

return Json(projects.Select(m => new SelectListItem { ProjectId = m.Description + "," + m.ID , ProjectName = m.Description }).ToList(), JsonRequestBehavior.AllowGet);

Now you can use both in the next operations just by spiting them like:

var _both = value.split(',');//value: returned value from the view