0

I want to search result from db andy show on same view using ajax but it is not happening. Here is my Index page where I defined the Search box and a table to show search result. Index View is

@{
    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>

My Controller Function is.

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);
}

My Partial View is

@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>

On click of search button it is going to AjaxSearch function but not showing result in Index view.

Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74
raja
  • 83
  • 2
  • 3
  • 16
  • All you doing is calling `ExecuteReader` which returns `SqlDataReader` object, and you code would be throwing [this exception](https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ) because `SqlDataReader` is not `IEnumerable`. You need to read the values from the `SqlDataReader` and assign then to new instances of `PostJob` –  Sep 29 '17 at 05:54
  • and also you are concatenating the search text in your query, this is dangerous as anyone can inject sql. – Jameel Hussain Sep 29 '17 at 05:58
  • [SQL injection](https://en.wikipedia.org/wiki/SQL_injection) –  Sep 29 '17 at 06:03

1 Answers1

0

You must map ExecuteReader result to object(PostJob).

In AjaxSearch action replace this line

var r = cmd.ExecuteReader();

with

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);
Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74