I am trying to validate a search box in MVC 3 using C# , so that when a user enters nothing a message will appear in the ViewBag saying ‘Please enter a Search Query’.Any help would be much appreciated.
public ViewResult Index(string sortOrder, String searchString)
{
ViewBag.NamesSortParm = String.IsNullOrEmpty(sortOrder) ? "Name desc" : "";
ViewBag.UserSortParm = sortOrder == "UserID" ? "Name" : "Song";
var User = from s in db.User select s;
if (!String.IsNullOrEmpty(searchString))
{
User = Users.Where(s => s.Name.ToUpper().Contains(searchString.ToUpper())
|| s.Songs.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "Name":
Users = Users.OrderByDescending(s => s.Name);
break;
case "Songs":
Users = Users.OrderByDescending(s => s.Song);
break;
default:
Users = Users.OrderBy(s => s.Name);
break;
}
// ...
}
You should try to create simple view as Ben said. But what’s more add some metadata atributes to your class (then you can work on your class). It should look like this:
Then when you make some strongly typed view, when user doesn’t write anything in SearchString, validation message will appear 🙂