【发布时间】:2017-09-29 05:38:09
【问题描述】:
我想使用 ajax 在同一视图上搜索来自 db andy show 的结果,但它没有发生。这是我的索引页面,我在其中定义了搜索框和一个表格来显示搜索结果。 索引视图是
@{
Layout = null;
}
@model IEnumerable<BR.Models.PostJob>
@using (Ajax.BeginForm("AjaxSearch", "Student",
new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" }))
{
<input type="text" name="q" />
<input type="submit" value="Search" />
}
My Table to show Searched result is.
<table id="searchResults">
</table>
我的控制器功能是。
public PartialViewResult AjaxSearch(string q)
{
SqlDataReader dr;
SqlConnection con = new SqlConnection("Data Source=IT-INTERN3;Initial Catalog=bridging_the_gap;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "select * from Jobs where job_title ='" + q + "'";
cmd.Connection = con;
var r = cmd.ExecuteReader();
return this.PartialView(r);
}
我的部分观点是
@model IEnumerable<BR.Models.PostJob>
<table>
<tr>
<th>
id
</th>
<th>
job_title
</th>
<th>
job_description
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@item.id
</td>
<td>
@item.job_title
</td>
<td>
item.job_description
</td>
</tr>
}
</table>
点击搜索按钮时,它会转到 AjaxSearch 功能,但不会在索引视图中显示结果。
【问题讨论】:
-
你所做的只是调用
ExecuteReader,它返回SqlDataReader对象,你的代码会抛出this exception,因为SqlDataReader不是IEnumerable<BR.Models.PostJob>。您需要从SqlDataReader中读取值,然后将其分配给PostJob的新实例 -
而且你正在连接查询中的搜索文本,这很危险,因为任何人都可以注入 sql。
标签: ajax asp.net-mvc