This is a migrated thread and some comments may be shown as answers.

Set ComboBox by the model (in Edit mode)

2 Answers 135 Views
ComboBox
This is a migrated thread and some comments may be shown as answers.
Ivan
Top achievements
Rank 1
Ivan asked on 16 Jan 2013, 12:06 AM
Hi!
I have two models in one-more relation:   One "Region" to more "Punkt"
I'am using ASP.NET MVC4 and have Edit page of "Punkt" Model record. The Edit page has ComboBox populated with Regions but which I have to set to adequate Region (where Punkt belongs to).

The problem: I don't know how to set ComboBox to adequate Punkt option. 

Here is PunktController:
// GET: /Punkt/Edit/5
public ActionResult Edit(int id = 0)
{
    Punkt punkt = db.Punktovi.Find(id);
    
    if (punkt == null)
    {
        return HttpNotFound();
    }
 
    ViewBag.MaticniRegionId = new SelectList(db.Regioni, "RegionId", "Name", punkt.MaticniRegionId);
    return View(punkt);
}

//THIS IS MY METHOD USED FOR POPULATING COMBOBOX (SEE: EDIT view)
public ActionResult getRegioni()
{
    if (Request.IsAjaxRequest())
    {
        var ISPISContext = new ISPISContext();
        return Json(ISPISContext.Regioni.Select(r => new { RegionId = r.RegionId, Name = r.Name }), JsonRequestBehavior.AllowGet);
    }
    return View();
}

Here is Edit.cshtml view:
@(Html.Kendo().ComboBox()
    .Name("MaticniRegionId")
    .Placeholder("Select region...")
    .DataTextField("Name")
    .DataValueField("RegionId")
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("getRegioni", "Punkt");
        });
    })
    .Suggest(true)
)

2 Answers, 1 is accepted

Sort by
0
Vladimir Iliev
Telerik team
answered on 17 Jan 2013, 03:14 PM
Hi Ivan,

 
Basically if the Punkt model contains property with current region ID you can use the ComboBoxFor and bind it to that property - please check the example below:

//If the model contains Region property:
@(Html.Kendo().ComboBoxFor(Model => Model.Region)
     //set the Text and Value fields
     .DataTextField("Name")
     .DataValueField("RegionId")
     .DataSource(source => {
         //set the action and the controller
         source.Read("Read", "Home");
     })
)
Kind Regards,
Vladimir Iliev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Ivan
Top achievements
Rank 1
answered on 18 Jan 2013, 08:40 PM
Thanks! It works.
Tags
ComboBox
Asked by
Ivan
Top achievements
Rank 1
Answers by
Vladimir Iliev
Telerik team
Ivan
Top achievements
Rank 1
Share this question
or