2014-12-09 4 views
1

Иногда мне нравится использовать реализации HTML5/Javascript в системе Kendo, потому что вы можете немного облегчить некоторые вещи. В этом случае мне нужно знать количество результатов, чтобы я мог отображать сетку кендо или нет, однако в других случаях мне нужно изменить источник данных на основе ввода пользователя на стороне клиента. К сожалению, вы не можете получить число результатов или изменить источник данных (насколько мне известно) с использованием оберток MVC. Как я могу вызвать контроллер с помощью Javascript-реализации источника данных Kendo?Javascript Kendo Datasource, вызывающий MVC-контроллер

ответ

4

Я был в состоянии получить эту работу, используя следующий код:

Контроллер:

public ActionResult GetStuff(string parameter) 
{ 
    // Get your data here ... 
    var data = GetData(parameter); 

    return Json(data, JsonRequestBehavior.AllowGet); 

} // end 

Markup/cshtml:

<div id='myGrid'></div> 

<script> 

    $(document).ready(function() { 

     // Define the dataSource, note that the schema elements are specified 
     var dataSource = new kendo.data.DataSource({ 
      dataType: "json", 
      type: "GET", 
      transport: { 
       read: '@Url.Action("MethodName", "ControllerName", new {parameter = myParameter})'   
      },    
      schema: { 
       data: "Stuff", 
       total: "TotalNumberofStuff", 
       errors: "ErrorMessage" 
      } 
     }); 
    } 

    // Call fetch on the dataSource - this gets the data - the fetch method will make only one call. 
    // Please note that the datasource fetch call is async, so we must use it's results within the fetch function. 
    dataSource.fetch(function() { 

     var numberOfItems = dataSource.total(); 

     if (numberOfItems == 0) { 
      // If 0 items are returned show the label that says there are no items 
      $("#myGrid").append("<p><label style='font-size: small; color: red;'>-- No Items --</label></p>"); 
     } 
     else { 
      $("#myGrid").kendoGrid({ 
       dataSource: dataSource, 
       height: function() { 
        return (numberOfItems >= 1 && numberOfItems <= 5) ? null : "225"; 
       }, 
       columns: [ 
         { field: "StuffId", title: "Id", width: 150 }, 
         { field: "Stuff", title: "Stuff", width: 150 } 
        ] 
      }); 
     } 
    }); 

</script> 
Смежные вопросы