Вопрос

I'm trying to include a Kendo UI ASP.NET MVC Grid on the Edit page of my MVC application and I would like to restrict that grid to only return values from the current route id. I've been researching ways to do this, but can't find anything that's exactly what I need, or I'm just too new at this to connect the dots.

My ideas so far are to either apply a filter to the DataSource or send a parameter to the controller and have it restrict the DataSourceResult.

For the DataSource filter in the view, I can do this:

.Filter(filters => { filters.Add(d => d.CompanyId).IsEqualTo(2); })

But I can't figure out how to replace the hardcoded 2 with the value from, say, @ViewContext.RouteData.Values["id"], or something.

Passing a parameter to the controller, I can get the following:

public ActionResult Divisions_Read([DataSourceRequest]DataSourceRequest request, int id)
{
    using (var db = new AppContext())
    {
        IQueryable<Division> divisions = db.Divisions;
        DataSourceResult result = divisions.ToDataSourceResult(request, division => new DivisionViewModel
        {
            DivisionId = division.DivisionId,
            CompanyId = division.CompanyId,
            CountryId = division.CountryId,
            DivisionName = division.DivisionName
        });
        return Json(result);
    }
}

But I have no idea how to use that id to basically add a "where CompanyId = Id" statement to the result.

Any ideas on what the best way to do this would be? Am I missing something really obvious?

Thanks!

ETA: Passing the parameter to the Controller through the Read action, as suggested by mmillican and other places in my research, and changing

DataSourceResult result = divisions.ToDataSourceResult(request, division => new DivisionViewModel

to

DataSourceResult result = divisions.Where(c => c.CompanyId == companyId).ToDataSourceResult(request, division => new DivisionViewModel

did the trick. That extra bit in the controller was what I was looking for, but couldn't seem to find anywhere.

Это было полезно?

Решение

Assuming you have a model for your page that looks like this:

public class MyViewModel
{
    public int Id { get; set; } // assuming Id is what you want to filter by

    // .. other VM properties
}

you can do something like this in your grid data binding

.DataSource(ds => ds
    .Ajax()
    .Model(mdl => mdl.Id(x => x.Id))
    .Read("Divisions_Read", "Divisions", new { id = Model.Id })
)

in your controller, you would set the model's Id property to whatever ID that is in the route.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top