简体   繁体   中英

Rebind grid with combobox, how to get selected value?

I work with Telerik-MVC and I'm trying to rebind a grid when I change the value of a combobox. Everything seems working except I can't get selected value of my combobox. Here is my code :

Grid :

@{Html.Telerik().Grid(Model)
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(o => o.Col1);
            columns.Bound(o => o.Col2);
            columns.Bound(o => o.Col3);
        })
        .DataBinding(dataBinding => dataBinding.Ajax()
             .Select("_MyAction", "MyController")
        )
        .ClientEvents(events => events.OnDataBinding("Grid_onDataBinding"))
}

Combobox :

@(Html.Telerik().ComboBox()
        .Name("ComboBox")
        .HtmlAttributes(new { id = "ComboBoxCode" })
        .BindTo(new SelectList(Model.GroupBy(x => x.Code)
                              .Select(o => o.First()).ToList(), 
                              "Code", "Code"))
        .ClientEvents(events => events
                .OnChange("onComboBoxChange")
        )
)

Script :

function onComboBoxChange(e) {
    $("#Grid").data("tGrid").rebind();
}
function Grid_onDataBinding(e) {
    var code = /* I need to get the combobox value here */;
    e.data = { myCode: code };
}

Controller :

    [GridAction]
    public ActionResult _MyAction(string myCode)
    {
        Console.WriteLine("Code : " + code);
        /*
            Set new model here
        */
        return View(new GridModel(newModel));
    }

I tried things like :

var e = document.getElementById("ComboBoxCode");
var code = e.options[e.selectedIndex].text;

But it doesn't work. Can you tell me how to fix this problem and get the right value ?

The problem is that when you rebind the grid, you didn't really use the ComboBox selected value. Your onComboBoxChange function tells the grid to rebind, which it does by going to the _MyAction method. At no point did you pass in the ComboBox value. What you should do is before databinding, grab the selected value and pass it to your controller action. See http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-grid-client-api-and-events.html#OnDataBinding for details. Something like this:

function Grid_onDataBinding(e) {
    var combobox = $('#ComboBox').data('tComboBox');
    e.data = { code: combobox.value };
}

(Note that I actually haven't done any work with the ComboBox, so this isn't tested, but this should at least get you on the right path. See ComboBox documentation .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM