Dynamic Query Builder for ASP.Net-MVC - Using jQuery QueryBuilder, DataTables, and dynamic-linq-query-builder












0















I'm trying to accomplish the following Tasks:




  1. Create a visual expression/ query builder for ASP.NET-MVC.

  2. Pass the resulting query to DataTables.


This question is about Task 1 as that's where I'm stuck. I have posted Task 2 to provide more background information.



To achieve Task 1 I'm using the jQuery QueryBuilder - a jQuery plugin to create user friendly queries. On the QueryBuilder website there is a listing for .NET under the Backends section (https://querybuilder.js.org/#backends). They recommend to use the dynamic-linq-query-builder by Castle-it (https://github.com/castle-it/dynamic-linq-query-builder).



Here is my issue:



The dynamic-linq-query-builder all seems to be built with static classes. I want to retrieve the data from my database but from my research online I'm not able to initiate a dbcontext within a static class.



Dynamic-linq-query provides a PersonBuilder class to deserialize a JSON data and they include a TestData string:



 public static class PersonBuilder
{
public static List<PersonRecord> GetPeople()
{
var result = new List<PersonRecord>();

var testData = TestData;

var personRecords = JsonConvert.DeserializeObject<List<PersonRecord>>(testData);

return personRecords;

}

private static string TestData
{
get
{
return @"
[
{
""FirstName"": ""Jane"",

""LastName"": ""Hansen"",
""Birthday"": ""1969-12-31T16:00:00-08:00"",
""Address"": ""P.O. Box 492, 4607 Tempus, Rd."",
""City"": ""Polatlı"",
""State"": ""Ankara"",
...
...
...


Then in the HomeController they are using the following to filter the query:



[HttpPost]
public JsonResult Index(FilterRule obj)
{
var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();

return Json(people);


}


And here is their QueryBuilder implementation and jQuery logic to read out the results.



  <script type="text/javascript">
$(function() {
// Handler for .ready() called.
var tableData = ;

var filterDefinition = @Html.Raw(ViewBag.FilterDefinition);
var customFilters = {
condition: 'AND',
rules:
};
var jqueryQueryBuilder = $('#jquery-query-builder');
var jqueryQueryBuilderDom = jqueryQueryBuilder.queryBuilder({
plugins: ['bt-tooltip-errors', 'filter-description'],
//allow_groups: 0,
allow_empty: true,
filters: filterDefinition,
rules: customFilters,
icons: {
add_group: 'fa fa-plus-square',
add_rule: 'fa fa-plus-circle',
remove_group: 'fa fa-minus-square',
remove_rule: 'fa fa-minus-circle',
error: 'fa fa-exclamation-triangle',
sortable: 'fa fa-exclamation-triangle'
}
});

var convertArraysToCommaDelimited = function(obj) {
if (obj != null) {
if (obj.hasOwnProperty("value")) {
if( Object.prototype.toString.call( obj.value ) === '[object Array]' ) {
obj.value = obj.value.join(", ");
}
}
if (obj.hasOwnProperty("rules") && obj.rules != null) {
for (var i = 0; i < obj.rules.length; i++) {
convertArraysToCommaDelimited(obj.rules[i]);
}
}
}
}
var getRules = function() {
try {
var res = jqueryQueryBuilder.queryBuilder('getRules');
convertArraysToCommaDelimited(res);
return res;
} catch (ex) {
//console.log(ex);
return null;
}
}

var buildTable;
var filterData = function() {

$.ajax({
type: 'POST',
url: "../Home/Index",
data: JSON.stringify(getRules()),
success: function (returnPayload) {
tableData = returnPayload;
buildTable();
console && console.log ("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log ("request failed");
},
dataType: "json",
contentType: "application/json",
processData: false,
async: true
});
}



$('#applyFilter').on('click', function() {
filterData();
});
buildTable = function() {
var tbody = $('#data-table tbody'),
props = ["FirstName", "LastName", "Birthday", "Age", "Address", "City", "State", "ZipCode"];
tbody.empty();
$.each(tableData, function(i, reservation) {
var tr = $('<tr>');
$.each(props, function(i, prop) {
$('<td>').html(reservation[prop]).appendTo(tr);
});
tbody.append(tr);
});
};

filterData();

});

</script>


You'll notice that they've created a buildTable function. Later I would like to replace this with a DataTable implementation.



What I've tried:



I have tried to initiate a dbcontext with LINQ in the PersonBuilder class. The issue is that this class was static. I simply removed the static definition of the PersonBuilder class. Here is my implementation:



public List<PersonRecord> GetPeople()
{
IQueryable<PersonRecord> query = DbContext.PersonRecord;


var data = query.Select(asset => new Asset
{
data1 = PersonRecord.data1,
data2 = PersonRecord.data2,
...
...

}).ToList();

return data;
}


The issue I'm experiencing is that the HomeController is now throwing the following error:




CS0120: An object reference is required for the nonstatic field,
method, or property 'member'




At the following line:



var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();


Not quite sure how to get around this since it seems the entire library is built with static classes?



What do you guys think?










share|improve this question





























    0















    I'm trying to accomplish the following Tasks:




    1. Create a visual expression/ query builder for ASP.NET-MVC.

    2. Pass the resulting query to DataTables.


    This question is about Task 1 as that's where I'm stuck. I have posted Task 2 to provide more background information.



    To achieve Task 1 I'm using the jQuery QueryBuilder - a jQuery plugin to create user friendly queries. On the QueryBuilder website there is a listing for .NET under the Backends section (https://querybuilder.js.org/#backends). They recommend to use the dynamic-linq-query-builder by Castle-it (https://github.com/castle-it/dynamic-linq-query-builder).



    Here is my issue:



    The dynamic-linq-query-builder all seems to be built with static classes. I want to retrieve the data from my database but from my research online I'm not able to initiate a dbcontext within a static class.



    Dynamic-linq-query provides a PersonBuilder class to deserialize a JSON data and they include a TestData string:



     public static class PersonBuilder
    {
    public static List<PersonRecord> GetPeople()
    {
    var result = new List<PersonRecord>();

    var testData = TestData;

    var personRecords = JsonConvert.DeserializeObject<List<PersonRecord>>(testData);

    return personRecords;

    }

    private static string TestData
    {
    get
    {
    return @"
    [
    {
    ""FirstName"": ""Jane"",

    ""LastName"": ""Hansen"",
    ""Birthday"": ""1969-12-31T16:00:00-08:00"",
    ""Address"": ""P.O. Box 492, 4607 Tempus, Rd."",
    ""City"": ""Polatlı"",
    ""State"": ""Ankara"",
    ...
    ...
    ...


    Then in the HomeController they are using the following to filter the query:



    [HttpPost]
    public JsonResult Index(FilterRule obj)
    {
    var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
    var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();

    return Json(people);


    }


    And here is their QueryBuilder implementation and jQuery logic to read out the results.



      <script type="text/javascript">
    $(function() {
    // Handler for .ready() called.
    var tableData = ;

    var filterDefinition = @Html.Raw(ViewBag.FilterDefinition);
    var customFilters = {
    condition: 'AND',
    rules:
    };
    var jqueryQueryBuilder = $('#jquery-query-builder');
    var jqueryQueryBuilderDom = jqueryQueryBuilder.queryBuilder({
    plugins: ['bt-tooltip-errors', 'filter-description'],
    //allow_groups: 0,
    allow_empty: true,
    filters: filterDefinition,
    rules: customFilters,
    icons: {
    add_group: 'fa fa-plus-square',
    add_rule: 'fa fa-plus-circle',
    remove_group: 'fa fa-minus-square',
    remove_rule: 'fa fa-minus-circle',
    error: 'fa fa-exclamation-triangle',
    sortable: 'fa fa-exclamation-triangle'
    }
    });

    var convertArraysToCommaDelimited = function(obj) {
    if (obj != null) {
    if (obj.hasOwnProperty("value")) {
    if( Object.prototype.toString.call( obj.value ) === '[object Array]' ) {
    obj.value = obj.value.join(", ");
    }
    }
    if (obj.hasOwnProperty("rules") && obj.rules != null) {
    for (var i = 0; i < obj.rules.length; i++) {
    convertArraysToCommaDelimited(obj.rules[i]);
    }
    }
    }
    }
    var getRules = function() {
    try {
    var res = jqueryQueryBuilder.queryBuilder('getRules');
    convertArraysToCommaDelimited(res);
    return res;
    } catch (ex) {
    //console.log(ex);
    return null;
    }
    }

    var buildTable;
    var filterData = function() {

    $.ajax({
    type: 'POST',
    url: "../Home/Index",
    data: JSON.stringify(getRules()),
    success: function (returnPayload) {
    tableData = returnPayload;
    buildTable();
    console && console.log ("request succeeded");
    },
    error: function (xhr, ajaxOptions, thrownError) {
    console && console.log ("request failed");
    },
    dataType: "json",
    contentType: "application/json",
    processData: false,
    async: true
    });
    }



    $('#applyFilter').on('click', function() {
    filterData();
    });
    buildTable = function() {
    var tbody = $('#data-table tbody'),
    props = ["FirstName", "LastName", "Birthday", "Age", "Address", "City", "State", "ZipCode"];
    tbody.empty();
    $.each(tableData, function(i, reservation) {
    var tr = $('<tr>');
    $.each(props, function(i, prop) {
    $('<td>').html(reservation[prop]).appendTo(tr);
    });
    tbody.append(tr);
    });
    };

    filterData();

    });

    </script>


    You'll notice that they've created a buildTable function. Later I would like to replace this with a DataTable implementation.



    What I've tried:



    I have tried to initiate a dbcontext with LINQ in the PersonBuilder class. The issue is that this class was static. I simply removed the static definition of the PersonBuilder class. Here is my implementation:



    public List<PersonRecord> GetPeople()
    {
    IQueryable<PersonRecord> query = DbContext.PersonRecord;


    var data = query.Select(asset => new Asset
    {
    data1 = PersonRecord.data1,
    data2 = PersonRecord.data2,
    ...
    ...

    }).ToList();

    return data;
    }


    The issue I'm experiencing is that the HomeController is now throwing the following error:




    CS0120: An object reference is required for the nonstatic field,
    method, or property 'member'




    At the following line:



    var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();


    Not quite sure how to get around this since it seems the entire library is built with static classes?



    What do you guys think?










    share|improve this question



























      0












      0








      0








      I'm trying to accomplish the following Tasks:




      1. Create a visual expression/ query builder for ASP.NET-MVC.

      2. Pass the resulting query to DataTables.


      This question is about Task 1 as that's where I'm stuck. I have posted Task 2 to provide more background information.



      To achieve Task 1 I'm using the jQuery QueryBuilder - a jQuery plugin to create user friendly queries. On the QueryBuilder website there is a listing for .NET under the Backends section (https://querybuilder.js.org/#backends). They recommend to use the dynamic-linq-query-builder by Castle-it (https://github.com/castle-it/dynamic-linq-query-builder).



      Here is my issue:



      The dynamic-linq-query-builder all seems to be built with static classes. I want to retrieve the data from my database but from my research online I'm not able to initiate a dbcontext within a static class.



      Dynamic-linq-query provides a PersonBuilder class to deserialize a JSON data and they include a TestData string:



       public static class PersonBuilder
      {
      public static List<PersonRecord> GetPeople()
      {
      var result = new List<PersonRecord>();

      var testData = TestData;

      var personRecords = JsonConvert.DeserializeObject<List<PersonRecord>>(testData);

      return personRecords;

      }

      private static string TestData
      {
      get
      {
      return @"
      [
      {
      ""FirstName"": ""Jane"",

      ""LastName"": ""Hansen"",
      ""Birthday"": ""1969-12-31T16:00:00-08:00"",
      ""Address"": ""P.O. Box 492, 4607 Tempus, Rd."",
      ""City"": ""Polatlı"",
      ""State"": ""Ankara"",
      ...
      ...
      ...


      Then in the HomeController they are using the following to filter the query:



      [HttpPost]
      public JsonResult Index(FilterRule obj)
      {
      var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
      var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();

      return Json(people);


      }


      And here is their QueryBuilder implementation and jQuery logic to read out the results.



        <script type="text/javascript">
      $(function() {
      // Handler for .ready() called.
      var tableData = ;

      var filterDefinition = @Html.Raw(ViewBag.FilterDefinition);
      var customFilters = {
      condition: 'AND',
      rules:
      };
      var jqueryQueryBuilder = $('#jquery-query-builder');
      var jqueryQueryBuilderDom = jqueryQueryBuilder.queryBuilder({
      plugins: ['bt-tooltip-errors', 'filter-description'],
      //allow_groups: 0,
      allow_empty: true,
      filters: filterDefinition,
      rules: customFilters,
      icons: {
      add_group: 'fa fa-plus-square',
      add_rule: 'fa fa-plus-circle',
      remove_group: 'fa fa-minus-square',
      remove_rule: 'fa fa-minus-circle',
      error: 'fa fa-exclamation-triangle',
      sortable: 'fa fa-exclamation-triangle'
      }
      });

      var convertArraysToCommaDelimited = function(obj) {
      if (obj != null) {
      if (obj.hasOwnProperty("value")) {
      if( Object.prototype.toString.call( obj.value ) === '[object Array]' ) {
      obj.value = obj.value.join(", ");
      }
      }
      if (obj.hasOwnProperty("rules") && obj.rules != null) {
      for (var i = 0; i < obj.rules.length; i++) {
      convertArraysToCommaDelimited(obj.rules[i]);
      }
      }
      }
      }
      var getRules = function() {
      try {
      var res = jqueryQueryBuilder.queryBuilder('getRules');
      convertArraysToCommaDelimited(res);
      return res;
      } catch (ex) {
      //console.log(ex);
      return null;
      }
      }

      var buildTable;
      var filterData = function() {

      $.ajax({
      type: 'POST',
      url: "../Home/Index",
      data: JSON.stringify(getRules()),
      success: function (returnPayload) {
      tableData = returnPayload;
      buildTable();
      console && console.log ("request succeeded");
      },
      error: function (xhr, ajaxOptions, thrownError) {
      console && console.log ("request failed");
      },
      dataType: "json",
      contentType: "application/json",
      processData: false,
      async: true
      });
      }



      $('#applyFilter').on('click', function() {
      filterData();
      });
      buildTable = function() {
      var tbody = $('#data-table tbody'),
      props = ["FirstName", "LastName", "Birthday", "Age", "Address", "City", "State", "ZipCode"];
      tbody.empty();
      $.each(tableData, function(i, reservation) {
      var tr = $('<tr>');
      $.each(props, function(i, prop) {
      $('<td>').html(reservation[prop]).appendTo(tr);
      });
      tbody.append(tr);
      });
      };

      filterData();

      });

      </script>


      You'll notice that they've created a buildTable function. Later I would like to replace this with a DataTable implementation.



      What I've tried:



      I have tried to initiate a dbcontext with LINQ in the PersonBuilder class. The issue is that this class was static. I simply removed the static definition of the PersonBuilder class. Here is my implementation:



      public List<PersonRecord> GetPeople()
      {
      IQueryable<PersonRecord> query = DbContext.PersonRecord;


      var data = query.Select(asset => new Asset
      {
      data1 = PersonRecord.data1,
      data2 = PersonRecord.data2,
      ...
      ...

      }).ToList();

      return data;
      }


      The issue I'm experiencing is that the HomeController is now throwing the following error:




      CS0120: An object reference is required for the nonstatic field,
      method, or property 'member'




      At the following line:



      var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();


      Not quite sure how to get around this since it seems the entire library is built with static classes?



      What do you guys think?










      share|improve this question
















      I'm trying to accomplish the following Tasks:




      1. Create a visual expression/ query builder for ASP.NET-MVC.

      2. Pass the resulting query to DataTables.


      This question is about Task 1 as that's where I'm stuck. I have posted Task 2 to provide more background information.



      To achieve Task 1 I'm using the jQuery QueryBuilder - a jQuery plugin to create user friendly queries. On the QueryBuilder website there is a listing for .NET under the Backends section (https://querybuilder.js.org/#backends). They recommend to use the dynamic-linq-query-builder by Castle-it (https://github.com/castle-it/dynamic-linq-query-builder).



      Here is my issue:



      The dynamic-linq-query-builder all seems to be built with static classes. I want to retrieve the data from my database but from my research online I'm not able to initiate a dbcontext within a static class.



      Dynamic-linq-query provides a PersonBuilder class to deserialize a JSON data and they include a TestData string:



       public static class PersonBuilder
      {
      public static List<PersonRecord> GetPeople()
      {
      var result = new List<PersonRecord>();

      var testData = TestData;

      var personRecords = JsonConvert.DeserializeObject<List<PersonRecord>>(testData);

      return personRecords;

      }

      private static string TestData
      {
      get
      {
      return @"
      [
      {
      ""FirstName"": ""Jane"",

      ""LastName"": ""Hansen"",
      ""Birthday"": ""1969-12-31T16:00:00-08:00"",
      ""Address"": ""P.O. Box 492, 4607 Tempus, Rd."",
      ""City"": ""Polatlı"",
      ""State"": ""Ankara"",
      ...
      ...
      ...


      Then in the HomeController they are using the following to filter the query:



      [HttpPost]
      public JsonResult Index(FilterRule obj)
      {
      var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
      var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();

      return Json(people);


      }


      And here is their QueryBuilder implementation and jQuery logic to read out the results.



        <script type="text/javascript">
      $(function() {
      // Handler for .ready() called.
      var tableData = ;

      var filterDefinition = @Html.Raw(ViewBag.FilterDefinition);
      var customFilters = {
      condition: 'AND',
      rules:
      };
      var jqueryQueryBuilder = $('#jquery-query-builder');
      var jqueryQueryBuilderDom = jqueryQueryBuilder.queryBuilder({
      plugins: ['bt-tooltip-errors', 'filter-description'],
      //allow_groups: 0,
      allow_empty: true,
      filters: filterDefinition,
      rules: customFilters,
      icons: {
      add_group: 'fa fa-plus-square',
      add_rule: 'fa fa-plus-circle',
      remove_group: 'fa fa-minus-square',
      remove_rule: 'fa fa-minus-circle',
      error: 'fa fa-exclamation-triangle',
      sortable: 'fa fa-exclamation-triangle'
      }
      });

      var convertArraysToCommaDelimited = function(obj) {
      if (obj != null) {
      if (obj.hasOwnProperty("value")) {
      if( Object.prototype.toString.call( obj.value ) === '[object Array]' ) {
      obj.value = obj.value.join(", ");
      }
      }
      if (obj.hasOwnProperty("rules") && obj.rules != null) {
      for (var i = 0; i < obj.rules.length; i++) {
      convertArraysToCommaDelimited(obj.rules[i]);
      }
      }
      }
      }
      var getRules = function() {
      try {
      var res = jqueryQueryBuilder.queryBuilder('getRules');
      convertArraysToCommaDelimited(res);
      return res;
      } catch (ex) {
      //console.log(ex);
      return null;
      }
      }

      var buildTable;
      var filterData = function() {

      $.ajax({
      type: 'POST',
      url: "../Home/Index",
      data: JSON.stringify(getRules()),
      success: function (returnPayload) {
      tableData = returnPayload;
      buildTable();
      console && console.log ("request succeeded");
      },
      error: function (xhr, ajaxOptions, thrownError) {
      console && console.log ("request failed");
      },
      dataType: "json",
      contentType: "application/json",
      processData: false,
      async: true
      });
      }



      $('#applyFilter').on('click', function() {
      filterData();
      });
      buildTable = function() {
      var tbody = $('#data-table tbody'),
      props = ["FirstName", "LastName", "Birthday", "Age", "Address", "City", "State", "ZipCode"];
      tbody.empty();
      $.each(tableData, function(i, reservation) {
      var tr = $('<tr>');
      $.each(props, function(i, prop) {
      $('<td>').html(reservation[prop]).appendTo(tr);
      });
      tbody.append(tr);
      });
      };

      filterData();

      });

      </script>


      You'll notice that they've created a buildTable function. Later I would like to replace this with a DataTable implementation.



      What I've tried:



      I have tried to initiate a dbcontext with LINQ in the PersonBuilder class. The issue is that this class was static. I simply removed the static definition of the PersonBuilder class. Here is my implementation:



      public List<PersonRecord> GetPeople()
      {
      IQueryable<PersonRecord> query = DbContext.PersonRecord;


      var data = query.Select(asset => new Asset
      {
      data1 = PersonRecord.data1,
      data2 = PersonRecord.data2,
      ...
      ...

      }).ToList();

      return data;
      }


      The issue I'm experiencing is that the HomeController is now throwing the following error:




      CS0120: An object reference is required for the nonstatic field,
      method, or property 'member'




      At the following line:



      var people = PersonBuilder.GetPeople().BuildQuery(obj).ToList();


      Not quite sure how to get around this since it seems the entire library is built with static classes?



      What do you guys think?







      c# asp.net-mvc linq datatables jquery-query-builder






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 '18 at 23:11







      ipetduckies

















      asked Nov 20 '18 at 16:00









      ipetduckiesipetduckies

      115




      115
























          1 Answer
          1






          active

          oldest

          votes


















          0














          The main problem is that you're defining GetPeople() as non-static method inside PersonBuilder class which marked as static. As noted in MSDN documentation, static classes must contain only static members, including static methods (see the reason here).



          The CS0120 error indicates that you should use either static class with static method, or non-static class' instantiated constructor as object. If you want to use non-static method, the class should not marked as static, also the class constructor must be instantiated first before the method can be accessed:



          public class PersonBuilder
          {
          public List<PersonRecord> GetPeople()
          {
          IQueryable<PersonRecord> query = DbContext.PersonRecord;

          var data = query.Select(asset => new Asset
          {
          data1 = PersonRecord.data1,
          data2 = PersonRecord.data2,
          // other stuff

          }).ToList();

          return data;
          }
          }


          Usage



          [HttpPost]
          public JsonResult Index(FilterRule obj)
          {
          var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
          var personBuilder = new PersonBuilder(); // add constructor initialization first
          var people = personBuilder.GetPeople().BuildQuery(obj).ToList();

          return Json(people);
          }


          Related issue:



          How shouldi avoid the CS0120 error in my code?






          share|improve this answer
























          • hello, how would I handle this in a generic way, i.e. if I didnt know my Person type and simply was trying to load the objects to the builder. Specifically speaking, I have CSV files I am loading and converting to List. Another question, who can I access the linq query Posted back from the user

            – transformer
            Dec 14 '18 at 7:38













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396912%2fdynamic-query-builder-for-asp-net-mvc-using-jquery-querybuilder-datatables-a%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          The main problem is that you're defining GetPeople() as non-static method inside PersonBuilder class which marked as static. As noted in MSDN documentation, static classes must contain only static members, including static methods (see the reason here).



          The CS0120 error indicates that you should use either static class with static method, or non-static class' instantiated constructor as object. If you want to use non-static method, the class should not marked as static, also the class constructor must be instantiated first before the method can be accessed:



          public class PersonBuilder
          {
          public List<PersonRecord> GetPeople()
          {
          IQueryable<PersonRecord> query = DbContext.PersonRecord;

          var data = query.Select(asset => new Asset
          {
          data1 = PersonRecord.data1,
          data2 = PersonRecord.data2,
          // other stuff

          }).ToList();

          return data;
          }
          }


          Usage



          [HttpPost]
          public JsonResult Index(FilterRule obj)
          {
          var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
          var personBuilder = new PersonBuilder(); // add constructor initialization first
          var people = personBuilder.GetPeople().BuildQuery(obj).ToList();

          return Json(people);
          }


          Related issue:



          How shouldi avoid the CS0120 error in my code?






          share|improve this answer
























          • hello, how would I handle this in a generic way, i.e. if I didnt know my Person type and simply was trying to load the objects to the builder. Specifically speaking, I have CSV files I am loading and converting to List. Another question, who can I access the linq query Posted back from the user

            – transformer
            Dec 14 '18 at 7:38


















          0














          The main problem is that you're defining GetPeople() as non-static method inside PersonBuilder class which marked as static. As noted in MSDN documentation, static classes must contain only static members, including static methods (see the reason here).



          The CS0120 error indicates that you should use either static class with static method, or non-static class' instantiated constructor as object. If you want to use non-static method, the class should not marked as static, also the class constructor must be instantiated first before the method can be accessed:



          public class PersonBuilder
          {
          public List<PersonRecord> GetPeople()
          {
          IQueryable<PersonRecord> query = DbContext.PersonRecord;

          var data = query.Select(asset => new Asset
          {
          data1 = PersonRecord.data1,
          data2 = PersonRecord.data2,
          // other stuff

          }).ToList();

          return data;
          }
          }


          Usage



          [HttpPost]
          public JsonResult Index(FilterRule obj)
          {
          var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
          var personBuilder = new PersonBuilder(); // add constructor initialization first
          var people = personBuilder.GetPeople().BuildQuery(obj).ToList();

          return Json(people);
          }


          Related issue:



          How shouldi avoid the CS0120 error in my code?






          share|improve this answer
























          • hello, how would I handle this in a generic way, i.e. if I didnt know my Person type and simply was trying to load the objects to the builder. Specifically speaking, I have CSV files I am loading and converting to List. Another question, who can I access the linq query Posted back from the user

            – transformer
            Dec 14 '18 at 7:38
















          0












          0








          0







          The main problem is that you're defining GetPeople() as non-static method inside PersonBuilder class which marked as static. As noted in MSDN documentation, static classes must contain only static members, including static methods (see the reason here).



          The CS0120 error indicates that you should use either static class with static method, or non-static class' instantiated constructor as object. If you want to use non-static method, the class should not marked as static, also the class constructor must be instantiated first before the method can be accessed:



          public class PersonBuilder
          {
          public List<PersonRecord> GetPeople()
          {
          IQueryable<PersonRecord> query = DbContext.PersonRecord;

          var data = query.Select(asset => new Asset
          {
          data1 = PersonRecord.data1,
          data2 = PersonRecord.data2,
          // other stuff

          }).ToList();

          return data;
          }
          }


          Usage



          [HttpPost]
          public JsonResult Index(FilterRule obj)
          {
          var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
          var personBuilder = new PersonBuilder(); // add constructor initialization first
          var people = personBuilder.GetPeople().BuildQuery(obj).ToList();

          return Json(people);
          }


          Related issue:



          How shouldi avoid the CS0120 error in my code?






          share|improve this answer













          The main problem is that you're defining GetPeople() as non-static method inside PersonBuilder class which marked as static. As noted in MSDN documentation, static classes must contain only static members, including static methods (see the reason here).



          The CS0120 error indicates that you should use either static class with static method, or non-static class' instantiated constructor as object. If you want to use non-static method, the class should not marked as static, also the class constructor must be instantiated first before the method can be accessed:



          public class PersonBuilder
          {
          public List<PersonRecord> GetPeople()
          {
          IQueryable<PersonRecord> query = DbContext.PersonRecord;

          var data = query.Select(asset => new Asset
          {
          data1 = PersonRecord.data1,
          data2 = PersonRecord.data2,
          // other stuff

          }).ToList();

          return data;
          }
          }


          Usage



          [HttpPost]
          public JsonResult Index(FilterRule obj)
          {
          var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
          var personBuilder = new PersonBuilder(); // add constructor initialization first
          var people = personBuilder.GetPeople().BuildQuery(obj).ToList();

          return Json(people);
          }


          Related issue:



          How shouldi avoid the CS0120 error in my code?







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 3:07









          Tetsuya YamamotoTetsuya Yamamoto

          16.5k42240




          16.5k42240













          • hello, how would I handle this in a generic way, i.e. if I didnt know my Person type and simply was trying to load the objects to the builder. Specifically speaking, I have CSV files I am loading and converting to List. Another question, who can I access the linq query Posted back from the user

            – transformer
            Dec 14 '18 at 7:38





















          • hello, how would I handle this in a generic way, i.e. if I didnt know my Person type and simply was trying to load the objects to the builder. Specifically speaking, I have CSV files I am loading and converting to List. Another question, who can I access the linq query Posted back from the user

            – transformer
            Dec 14 '18 at 7:38



















          hello, how would I handle this in a generic way, i.e. if I didnt know my Person type and simply was trying to load the objects to the builder. Specifically speaking, I have CSV files I am loading and converting to List. Another question, who can I access the linq query Posted back from the user

          – transformer
          Dec 14 '18 at 7:38







          hello, how would I handle this in a generic way, i.e. if I didnt know my Person type and simply was trying to load the objects to the builder. Specifically speaking, I have CSV files I am loading and converting to List. Another question, who can I access the linq query Posted back from the user

          – transformer
          Dec 14 '18 at 7:38






















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53396912%2fdynamic-query-builder-for-asp-net-mvc-using-jquery-querybuilder-datatables-a%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)