0

I have a Partial View that uses a Model. The Partial View is empty, except for a textbox and a button.

The user will type a value into the text box and click the button.

I want to use Ajax to take the value typed in the textbox, and perform a search on the database. Then with the data returned, update the Partial View with using the Model.

My code so far -

<input id="searchValue" type="text" />   
<input id="searchButton" type="submit" value="submit" />

<div>
@if(Model != null)
{
    foreach(var stuff in Model.ListOfStuff)
    {
        <li>@stuff.value</li>  
    }
}
</div>

Any help would be greatly appreciated. Thanks!

2 Answers 2

2

This article will help you, just follow what they do and do the same applying their concepts to your code: Updating Partial Views with Unobtrusive AJAX in MVC 3

0
1

Give an ID to your Result Div so that it will be easy for us to do it via jQuery later to update.

<div id="resultDiv">
    <ul></ul>
</div>

Now addthis javascript code

$(function(){
  $("#searchButton").click(function(e){
     var key=$("#searchKey").val();
     $.getJSON("@Url.Action("search","Items")/"+key,function(data){
        var items="";
        $.each(data,function(index,item){
            items+="<li>"+item.Name+"</li>;
        });
        $("#resultDiv>ul").html(items);
     });
  });
});

Now we should have an action method which accepts the search key and return the Result in JSON format.

public ActionResult Search(string id)
{
  List<Product> productList=repo.GetSearchResultFromKey(id);
  return Json(productList,JsonRequestBehaviour.AllowGet);
}

Assuming we have a viewmodel called Product like below and our GetSearchResultFromKey method returns a collection of Product classs from our search key.

public class Product
{
  public string Name { set;get;}
}

What we are doing here is, when user clicks on the search button, we get the search key and make a call to the search action method and the method will return the list of Product in JSON format. We are iterating through the items in the JSON Response and creating the li items and adding that to the ul element.

Make sure you have jQuery included in the page.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.