Set ComboBox by the model (in Edit mode)

3 posts, 0 answers
  1. Ivan
    Ivan avatar
    3 posts
    Member since:
    Dec 2012

    Posted 15 Jan 2013 Link to this post

    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. Vladimir Iliev
    Admin
    Vladimir Iliev avatar
    2172 posts

    Posted 17 Jan 2013 Link to this post

    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!
  3. UI for ASP.NET MVC is VS 2017 Ready
  4. Ivan
    Ivan avatar
    3 posts
    Member since:
    Dec 2012

    Posted 18 Jan 2013 Link to this post

    Thanks! It works.
Back to Top