我希望使用ajax在相同的视图上搜索db安迪显示的结果,但这是不可能的。这里是“我的索引”页面,其中定义了搜索框和一个显示搜索结果的表。索引视图是
@{
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函数,但在索引视图中没有显示结果。
发布于 2017-09-29 05:57:36
必须将ExecuteReader结果映射到object(PostJob)。
在AjaxSearch操作中,替换该行
var r = cmd.ExecuteReader();使用
List<PostJob> results = new List<PostJob>();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.Read())
{
PostJob newItem = new PostJob();
newItem.id = dr.GetInt32(0); // 0 is id column order
newItem.job_title = dr.GetString(1); // 1 is job_title column order
newItem.job_description = dr.GetString(2);
results.Add(newItem);
}
}
return PartialView(results);https://stackoverflow.com/questions/46482402
复制相似问题