Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ViewData to pass data from Controller to View

I'm trying to pass data from a controller to view, and display these data. But after many tries I can't.

Controller code :

public ActionResult ValidSearch(ProductSearchParam gp)
{

    if (gp.IsCandidate)
    {
        ViewBag.abc="bob";
        List<ProductCandidate> prodClist = new List<ProductCandidate>();
        prodClist = Pcs.SearchParam(gp,0,100);
        ViewBag.total = prodClist.Count;
        return View("ValidSearchCandidate", prodClist);
    }
    else
    {
        List<Product> prodlist = new List<Product>();
        prodlist = Ps.SearchParam(gp,0,100);
        ViewBag.total = prodlist.Count;
        return View("ValidSearch", prodlist);
    }

    //return View();
}

View code :

<body>
    <div>

        <p>Bonjour @ViewBag.abc</p>

I've even try TempData or ViewBag, unsuccessfully.

I do not understand why the value is not getting passed to the View correctly Can someone help me to solve this ?

like image 684
Antoine Ravier Avatar asked Dec 19 '22 04:12

Antoine Ravier


1 Answers

Since you have set some property on the ViewData on the Controller, you will have it available on the ViewData on View. On the other hand, you have the TempData which is used when you need to transfer information between requests to another route (redirects to an action). For sample:

public ActionResult ValidSearch(ProductSearchParam gp)
{
   List<ProductCandidate> prodClist = new List<ProductCandidate>();

   ViewData["Nom"] = "bob";

   return View("ValidSearchCandidate", prodClist);
}

And in the view:

@ViewData["Nom"].ToString()

@foreach(var prod in  Model)
{
   <li>@prod.Name</li>
}
like image 133
Felipe Oriani Avatar answered Dec 21 '22 17:12

Felipe Oriani