【发布时间】:2020-05-06 16:16:39
【问题描述】:
我正在尝试查询 SQL 服务器以自动填充搜索结果而不重新加载页面。我有一个搜索框,其中包含可供选择的选项的下拉列表,我想显示具有搜索值的相似数据。
我将整个数据库表从控制器传递到视图,并使用一些简单的 html 进行客户端修饰,并使用 ajax 将搜索值传递回控制器
<div class="container">
<b>Search By : </b>
<select id="SearchBy">
<option value="errormsg">errormsg</option>
<option value="StackTrace">StackTrace</option>
</select><br /><br />
@Html.TextBox("Search")<input type="submit" id="SearchBtn" value="Search" /><br /><br />
<table class="table table-bordered">
<thead>
<tr>
<th width="24%">ErrorId</th>
<th width="4%">errordate</th>
<th width="24%">Url</th>
<th width="24%">StackTrace</th>
<th width="24%">errormsg</th>
</tr>
</thead>
<tbody id="DataSearching">
@foreach (var x in Model)
{
<tr class="table-success">
<td>@x.ErrorID</td>
<td>@x.errordate</td>
<td>@x.Url</td>
<td>@x.StackTrace</td>
<td>@x.errormsg</td>
</tr>
}
</tbody>
</table>
</div>
<script src="/js/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#SearchBtn").click(function () {
var SearchBy = $("#SearchBy").val();
var SearchValue = $("#Search").val();
var SetData = $("#DataSearching");
SetData.html("");
$.ajax({
type: "post",
url: "/Error/Find?SearchBy=" + SearchBy + "&SearchValue" + SearchValue,
contentType: "html",
success: function (result) {
if (result.length == 0) {
SetData.append('<tr style="color:red"><td colspan="3">No Match</td></tr>')
}
else {
$.each(result, function (index, value) {
var Data = "<tr>" +
"<td>" + value.ErrorID + "</td>" +
"<td>" + value.errordate + "</td>" +
"<td>" + value.Url + "</td>" +
"<td>" + value.StackTrace + "</td>" +
"<td>" + value.errormsg + "</td>";
SetData.append(Data);
});
}
}
});
});
})
</script>
此方法用于接收搜索值并与数据库进行比较,以将相似的值返回给视图:
public JsonResult GetSearchingData(string SearchBy, string SearchValue)
{
List<tblerror_msg> ErrorList = new List<tblerror_msg>();
if(SearchBy == "errormsg")
{
try
{
String errormsg = SearchValue;
ErrorList = db.tblerror_msg.Where(x => x.errormsg == SearchValue || SearchValue == null).ToList();
}
catch (FormatException)
{
Console.WriteLine("{0} Is Not an Error Message", SearchValue);
}
return Json(ErrorList, JsonRequestBehavior.AllowGet);
}
else
{
ErrorList = db.tblerror_msg.Where(x => x.StackTrace.StartsWith(SearchValue) || SearchValue == null).ToList();
return Json(ErrorList, JsonRequestBehavior.AllowGet);
}
}
当我搜索一个值时,表格消失并且没有返回任何内容。我是 jquery/ajax 的新手,所以如果没有错误,我不确定如何调试, 如何从我的 ajax 方法返回响应?
【问题讨论】:
标签: jquery ajax asp.net-mvc