Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string message from controller to view in MVC

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

like image 247
user3172140 Avatar asked Dec 26 '22 09:12

user3172140


1 Answers

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" });
like image 176
Brian Mains Avatar answered Feb 20 '23 17:02

Brian Mains