tags:

views:

49

answers:

1

I try to creat list for detail view. then put a search text box on the top of the list. Hope the search result will replace the list partially.

My control code like:

public ActionResult Index(int? page)
{
  Repository repository = new Repository();
  var listitems= repository.FindAllItems();
  return View(registry_page);
}

public ActionResult Search(string keyword)
{
  try
    {
     Repository repository = new Repository();     
     var listitems = repository.FindItemsByKeyWord(keyword);           
     return View("Index", registries);
    }
  catch
  {
    return View("Index");
   }
}

My View code like:

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>" type="text/javascript"></script>

<% using (Ajax.BeginForm("Search", new AjaxOptions { UpdateTargetId = "MyList" }))
   { %>
<p>
    Search:
    <input id="keyword" name="keyword" type="text" />
    <input type="submit" value="Go" />
</p>
<% } %>

<div id="MyList">
 <table idth="780px">
    ...

    <% foreach (var item in Model)
      { %>
      <tr>
      ...
      </tr>
    <% } %>
 </table>
</div>

When I submit the ajax form, it did reach the right action Searcn and I did get the right result from repository, but the list in the view wasn't replaced with the new result.

If I change search action like:

public ActionResult Search(string keyword)
{
 string teststring = "<div>This is a test string to replace the list</div>";
 return Content(teststring);
}

The list wil be replace by the test string. How to fix this problem?

A: 

You can pull MyList out into a Partial view, MyPartialList.ascx

Your search actionresult should then return this partial view, something like this:

public ActionResult Search(string keyword)
{
     Repository repository = new Repository();     
     var listitems = repository.FindItemsByKeyWord(keyword);           
     return PartialView("MyPartialList", listitems);
}

In the index view, render the initial list like this:

<div id="MyList">
  <% Html.RenderPartial("MyPartialList",Model); %>
</div>

Your partial, MyPartialList.ascx would look like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Item>>" %>
<table ..>
<% foreach(var item in Model){%>
  // print it out
<%}%>
</table>
Christian Dalager