4

I want to display a string message through a string variable by passing from controller to View.

Here is my controller code:

public ActionResult SearchProduct(string SearchString)
        {

            FlipcartDBContextEntities db = new FlipcartDBContextEntities();
            string noResult="Search Result Not Found";
            var products = from p in db.Products  select p;

            if (!String.IsNullOrEmpty(SearchString))
            {
                products = products.Where(s => s.ProductName.StartsWith(SearchString));
                return View(products);

            }

            else
            {

                return View(noResult);
            }

// Here i want to display the string value ei Message to the view.

please guide me. Am new to MVC

1 Answer 1

10

Change your controller to:

    public ActionResult SearchProduct(string SearchString)
    {

        FlipcartDBContextEntities db = new FlipcartDBContextEntities();
        string noResult="Search Result Not Found";
        var products = from p in db.Products  select p;

        if (!String.IsNullOrEmpty(SearchString))
        {
            products = products.Where(s => s.ProductName.StartsWith(SearchString));
            return View(products.ToList());

        }

        else
        {
            ViewBag.Message = noResult;
            return View(new List,Product>());
        }

You can pass the message from the server to the client via the ViewBag. Note that you have to return the same API from both sides of the if/else, so you can't pass a list of products one time and a string the other. In your view:

if (ViewBag.Message != null)
{
   <span>@ViewBag.Message</span>
}

Or don't do any of that and just put the message in the view based on the existence of a product list having items within the list.

// Model = Products returned; must make sure list returned is not null
if (Model.Count > 0)
{
   <span>Search Result not found</span>
}

Or even as another option you can create a model class:

public class SearchModel
{
   public List<Product> Products { get; set; }

   public string EmptyMessage { get; set; }
}

And return this via your view method:

//if
return View(new SearchModel { Products = products });
//else
return View(new SearchModel { EmptyMessage = "Search result Not Found" });
Sign up to request clarification or add additional context in comments.

1 Comment

The view model (the last example), IMHO, is the best way to go. Everyhting the view needs is passed in one object and the intent is very clear when you read the code.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.