【问题标题】:.Net MVC 4. Ajax.Net MVC 4. Ajax
【发布时间】: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&lt;BR.Models.PostJob&gt;。您需要从SqlDataReader 中读取值,然后将其分配给PostJob 的新实例
  • 而且你正在连接查询中的搜索文本,这很危险,因为任何人都可以注入 sql。

标签: ajax asp.net-mvc


【解决方案1】:

您必须将 ExecuteReader 结果映射到对象(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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多