MVC - C# -Passing data using ViewBag and ViewData to View from Controller



  • Using ViewBag to send object (string) from Home controller to View

         HomeController.cs
 
namespace MvcVersionFinder.Controllers
{
    public class HomeController : Controller
    {
  public ActionResult VBDemo() // ViewBagDemo
        {
            ViewBag.country = "India";
            return View();
        }
     }
}

         VbDemo.cshtml
@{
    ViewBag.Title = "VBDemo";
}

 @ViewBag.country
@ViewData["county"]



India
India

Even though I used ViewBag to create/pass 'country' variable. However, it seems that I can access 'country' through ViewData as well in View. Not sure if it is by design but I discovered accidently.

  • Using ViewData to send object (string) from Home controller to View

         HomeController.cs
 
namespace MvcVersionFinder.Controllers
{
    public class HomeController : Controller
    {
  public ActionResult VBDemo() // ViewBagDemo
        { 
            ViewData["County"] = "India";
            return View();
        }
     }
}

         VbDemo.cshtml
@{
    ViewBag.Title = "VBDemo";
}

 @ViewBag.country
@ViewData["county"]




India
India

No comments:

Post a Comment