Friday, January 15, 2016

Ajax.BeginForm Example - ASP.NET MVC

In this example I use an ajax form to load search results.

1) In my view I add the Ajax form.

The form invokes the "SearchResult" action

@using (Ajax.BeginForm("SearchResult", "Search", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "searchResults"
}))
{
    <input type="text" name="q" />
    <input type="submit" value="Search" />  
}

<table id="searchResults">

</table>

2) The Action

public PartialViewResult SearchResult(string q)
        {
            var books = BookDB.GetBooks().Where(r => r.Name.Contains(q) || String.IsNullOrEmpty(q)).Take(10);
            return PartialView("_SearchResults", books);
        }

3)  The partial view to display search results

@using MvcBookReview.Infrastructure
@model IEnumerable<MvcBookReview.Models.BookReview>

<table id="searchResults">
    @foreach(var item in Model)
    {
    <tr>
        <td>
            <table>
                <tr>
                    <td><b>Book:</b> @item.Name</td>
                </tr>
                <tr>
                    <td><b>Rating:</b> @item.Rating</td>
                </tr>
            </table>
        </td>
        <td>
            <div class="bookitem">
                @Html.Image(item.ImageUrl, item.AlternateText)
            </div>
        </td>
    </tr>
    }
</table>

Note: Here I use the custom helper created in an earlier post


The Result: 
From left to right
    1) Search all
    2) Search text = "TinTin"
    3) Search text = "Asterix"


No comments:

Post a Comment