MVC4 EF5 - Linq SqlQuery()之后的Ajax调用错误

时间:2016-05-11 11:48:09

标签: c# jquery ajax linq asp.net-mvc-4

我的观点看起来像

<form onsubmit="return Filter();" class="my-form">
  <input type="submit" value="Filter!" />
</form>

使用以下ajax调用

    $.ajax({
        url: "/Report/Filter/",
        cache: false,
        type: "POST",
        dataType: "html"
        data: { filterOption: selectedFilterOption, filterOptionValue: selectedFilterValue },
        success: function (data) {
            $('#filterResultDiv').html(data);
        },
        error: function (reponse) {
            alert("error : " + reponse);
        }
    });

调用此控制器方法

        [HttpPost]
        public ActionResult Filter(string filterOption, string filterOptionValue)
        {
            var filterCol = (FilterColumnName)System.Enum.Parse(typeof(FilterColumnName), filterOption);
            var singleFilter = new SingleFilter(filterCol, filterOptionValue);
            var entries = singleFilter.Filter();
            ...
            return PartialView("\\Places\\PartialReport", reportVM);
        }

并在调试此方法时发生错误

 public List<FilteredRow> Filter()
        {
            List<FilteredRow> result = new List<FilteredRow>();
            var ent = new Entities();

            var query = "SELECT * FROM V_Data WHERE " + this.GetFilterColumnName() + "= @p0";
            var dbObjects = ent.V_Data.SqlQuery(query, this.Value).ToList(); //<---- the ajax error function gets called after this line :(

            foreach (var obj in dbObjects)
            {
                var entry = new FilteredRow(obj);
                result.Add(entry);
            }

            return result;
        }

所以在var dbObjects = ent.V_Data.SqlQuery(query, this.Value).ToList();之后调用alert函数并显示&#34; error:[object Object]&#34; ...但Filter()方法也会向我的方法返回正确数量的过滤实体控制器方法。部分视图很快显示,然后页面重新加载。我错过了什么?

1 个答案:

答案 0 :(得分:0)

此查询适用于所有数据类型:

var valueParam = new SqlParameter("@p0", this.Value);
var dbObjects = ent.V_Data.SqlQuery("SELECT * FROM V_Data WHERE " + this.GetFilterColumnName() + " = @p0", valueParam);

在javascript中我必须使用

function Filter() {
      $.ajax({
                url: '@Url.Action("Filter")',
                cache: false,
                type: "GET",
                data: { filterOption: selectedFilterOption, filterOptionValue: selectedFilterValue },
                success: function (data) {
                    $('#filterResultDiv').html(data);                
                },
                error: function (reponse) {
                    alert("error : " + reponse.toString());
                }
            });
            return false; //<- this avoids the page refresh!
          }