0

Environment/technologies: Cshtml / Razor, ajax, jQuery, SQL Server 2008

I implemented a simple search for my cshtml web app as follows:

  1. Input textbox for entering the search
  2. jQuery to call ajax method to request for appropriate method to do search in SQL
  3. When I receive the response, I load it onto an existing "select" tag like below:

    success: function (response) {
    $("select#searchres").replaceWith(response);                        
    } 
    

    That means I replace the existing select with the output; my typical response is achieved as shown below:

    <select id="searchres">
    <option value=""></option>
    @foreach (var result in searchresults)
    {
        <option value="@result[0]">@result[2] @result[3] @result[4]</option>
    }
    </select>
    
  4. Output: the results load as expected into the select; however, when I select the values that were loaded into the dropdown, my request from them does not return anything; it's as if the content I loaded does not exist. Also, the jquery methods employed to capture the selected value and perform an action do not get fired.

  5. Further steps: I looked at the page source, and lo and behold, realized that the dropdown/select still shows as though it holds the original content.

Question: how do I resolve this? How do I get the page to recognise my "new" tag as well as its content and respond appropriately to interactions?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
stingray_
  • 564
  • 5
  • 13

2 Answers2

0

If your using asp.net MVC Asp.net MVC ModelState.Clear.

ModelState.Clear();
//before returning your select

Also when you rewrite html dynamically, you have to rebind the event. So if you have click or change event on your select, rebind them after appending the html.

Hope this help.

Community
  • 1
  • 1
Mathieu Labrie Parent
  • 2,598
  • 1
  • 9
  • 10
0

Make the following changes. Overwriting select removes all attached event handlers. Use .html() instead of .replaceWith() in order to retain the original select element with it's event handlers.

success: function (response) {
    $("#searchres").html( response );                        
} 

Remove <select ...> and </select>:

<option value=""></option>
@foreach (var result in searchresults)
{
    <option value="@result[0]">@result[2] @result[3] @result[4]</option>
}
PeterKA
  • 24,158
  • 5
  • 26
  • 48