Search code examples
htmlasp.netmodel-view-controllerdynamic

ASP.Net MVC4 display dynamic contents in _Layout.schtml


My _Layout.schtml has code below for displaying some static text in the top area of the main page.

<div>
    <span>some text</span>
</div>

I want to display dynamic contents (based on info from a database table). Basically, the table contains 4 columns: Selection, Text1, Text2 and Text3 If selection is 1, text1 should be displayed; If selection is 2, text2 should be displayed; If selection is 3, text3 should be displayed.

How can I achieve this? Thanks


Solution

  • Set the viewbag element inside ActionResult that uses _Layout.cshtml as its master page.

    public ActionResult Index()
    {
       //Get database table value;
       var data = db.table...
       if(data.selection == 1)
          ViewBag.Text = data.text1;
       else if(data.selection == 2)
          ViewBag.Text = data.text2;
       else
          ViewBag.Text = data.text3;
       return View();
    }
    

    Retrieve that ViewBag inside _Layout.cshtml

    <div>
        <span>@ViewBag.Text</span>
    </div>