Search code examples
c#asp.netasp.net-mvcrazorviewbag

call property to populate in model


Hey all new to the MVC world so I'm sure I am not doing something correct here. I am trying to call a function from the model page from my view index page to populate some tooltips.

In my model:

public class tips
{
    public List<string> allTips()
    {
        List<string> theTips = new List<string>();

        theTips.Add("example 1");
        theTips.Add("example 2");

        return theTips;
    }

    private List<string> _tips;
    public List<string> getTips { get { return _tips; } set { _tips = allTips(); } }
}

And in my view:

public ActionResult Index()
{
    var blah = new tips().getTips;

    ViewBag.pageTips = blah;

    return getMainData();
}

And then I have this on the razor page:

@Html.Raw(ViewBag.pageTips[1])

Which should display example 2 on the page but instead it just displays null as the value for the toolTips.

Currently it has a value of null when it gets to the return for the pageTips in my view.

So what would I be doing incorrectly? I put some stops here and there and notice that it never calls the allTips() function so that's a good starting place as to what I need to do in order to do that.

I just figured that calling the .getTips would fire off the theTips function?


Solution

  • You are misunderstanding the concept of setter and using it as an "initializer", a setter is meant to set the value, to change it in other word. if you want to initialize it do it in the constructor.

    Here you are using two different Lists, I don't really know why. A working code would be:

    public class tips
    {
        public tips()
        {
            _tips = new List<string>();
    
            _tips.Add("example 1");
            _tips.Add("example 2");
        }
    
        private List<string> _tips;
        public List<string> getTips { get { return _tips; } set { _tips = value; } }
    }
    

    Then in the controller:

    ViewBag.pageTips = new tips().getTips;
    

    Then call it this way in the view:

    @Html.Raw(ViewBag.pageTips[1])