Reputation:
I am creating an application that is boosting my C# skills nothing academic, so please can you help me am nearly finished and I want to be done by 12th Jan because am going on holiday.
The problem is I want to modify my code so it shows an error page when a search is not found for example I searched an event and it a page came up saying nothing is found and press this to go back. I am using MVC3 in C# here is my search code from my controller:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
using (var db = new UniversityNewsEntities1())
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date";
if (Request.HttpMethod == "GET")
{
searchString = currentFilter;
}
else
{
page = 1;
}
ViewBag.CurrentFilter = searchString;
var FullArticle = from a in db.NewsItems
select a;
if (!String.IsNullOrEmpty(searchString))
{
FullArticle = FullArticle.Where(a => a.Headline.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "Name desc":
FullArticle = FullArticle.OrderBy(a => a.Headline);
break;
case "Date":
FullArticle =FullArticle.OrderBy(a => a.Posted);
break;
case "Date desc":
FullArticle = FullArticle.OrderBy(a => a.Posted);
break;
default:
FullArticle = FullArticle.OrderByDescending(a => a.Posted);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(FullArticle.ToPagedList(pageNumber, pageSize));
}
}
This code fully works and all I need is a way that will inform who ever is using this when they search something and if its not found in the database a page will appear telling them nothing is found please go back via a hyper link. Am using ASP.NET MVC3 and this is my main controller and everything works up to know.
Upvotes: 2
Views: 350
Reputation: 10645
First check if any results have been found. Remove this line:
return View(FullArticle.ToPagedList(pageNumber, pageSize));
with something like
var results = FullArticle.ToPagedList(pageNumber, pageSize);
if (results.Any())
{
return View(results);
}
return RedirectToAction("Error");
You'll need to add a new controller action in NewsController
public ActionResult Error()
{
return View();
}
All the HTML for showing the error and the back link would go in a new view (Views/News/Error.cshtml), which you can ask Visual Studio to generate.
Upvotes: 4