Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a search functionality with partial view in asp.net mvc 4

I am using ASP.NET MVC 4 with entity framework model first.

In my "Masterpage.cshtml" I want to have a partial view which contains a textbox and a button.

The search is looking for the items title, if the text contains a items title it should display those items.

When a text is submitted the @renderbody() should show a view with the items.

My question is how can I do this in a good way? whats a good and easy approach?

So far I have done this:

Created a method in my repository that does the search function:

public List<News> Search(string query)
        {

            var queryz =  db.News.Where(x => x.Title.Contains(query));
            return queryz.ToList();
        }

Now when it comes to my Searchcontroller im kinda lost how to do this. Beacuse one actionresult need to be the partialview that has a string query parameter and other one that contains a view that will display the items?

What I have done right now is having the whole process in same actionresult:

 Repository rep = new Repository();
        [HttpPost]
        public ActionResult Search(string query)
        {
            var searchlist = rep.Search(query);

            var model = new ItemViewModel()
            {
                NewsList = new List<NewsViewModel>()
            };

            foreach (var NewsItems in searchlist)
            {
                FillProductToModel(model, NewsItems);
            }

            return View(model);
        }

        private void FillProductToModel(ItemViewModel model, News news)
        {
            var productViewModel = new NewsViewModel
            {

                Description = news.Description,
                NewsId = news.Id,
                Title = news.Title,
                link = news.Link,
                Imageurl = news.Image,
                PubDate = news.Date,
            };
            model.NewsList.Add(productViewModel);
        }

any kind of help is appreciated alot!

like image 314
Obsivus Avatar asked May 19 '13 17:05

Obsivus


People also ask

How many ways we can render partial view in MVC 4?

There are 5 different way of rendering a partial view.

How can create search box in ASP.NET MVC?

Click "File" -> "New" -> "Project...". Select Web from the installed template and choose the type of new project as ASP.NET Web Application. Provide a meaningful name and click OK. Select an empty template and choose the type as MVC for the ASP.Net project.

How do you render a partial view in layout MVC 4?

Creating Partial View To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view.

Can you define partial view in MVC?

A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.


1 Answers

You could use the following approach:

Index.cshtml

Have one DIV that calls the search controller action, and another that'll display the results.

<div id="search-form">
    @Html.Action("Search", "Home");  // GET action in controller that displays form
</div>
<div id="search-results">
</div>

_SearchFormPartial.cshtml

Create a partial view that'll contain the search form. You can use Ajax.BeginForm so when a user searches the results will be displayed in the search-results DIV in Index.cshtml by AJAX. UpdateTargetId specifies that we want to pass the results of the search to the search-results DIV.

@using (Ajax.BeginForm("Search", "Home", FormMethod.Post,
        new AjaxOptions
        {
            InsertionMode = InsertionMode.Replace,
            HttpMethod = "POST",
            UpdateTargetId = "search-results"
         }))
{
<div>
    @Html.TextBox("query")
    <input type="submit" value="Search" />
</div>      
}

Controller

In your controller you'll need one action to display the form (partial view above) and another to process the search query and retun another partial view that'll display the results:

[HttpGet]
public ActionResult Search()
{
    return PartialView("_SearchFormPartial");
}

[HttpPost]
public ActionResult Search(string query)
{
    if(query != null)
    {
        try
        {
            var searchlist = rep.Search(query);

            var model = new ItemViewModel()
            {
                NewsList = new List<NewsViewModel>()
            };

            return PartialView("_SearchResultsPartial", model);
        }
        catch (Exception e)
        {
            // handle exception
        }
    }
    return PartialView("Error");
}

_SearchResultsPartial.cshtml

This partial will display the results. It's strongly typed taking in an ItemViewModel.

@model Namespace.ViewModels.ItemViewModel
@if (Model.SearchResults.Count == 0)
{
    <h3 class="text-error">No items matched your search query!</h3>
}
else
{
    foreach (var result in Model.NewsList)
    {
        // display search results
    }
}
like image 190
MattSull Avatar answered Oct 13 '22 00:10

MattSull