Question

I am trying to centralize some rather static info, e.g. a user's name or a logo image URL. The code I'm cleaning up originally would look this information up in each controller action that needed it and set it within the strongly-typed model. This caused numerous blocks of the same (and sometimes slightly different, depending on the author) code to be repeated throughout the application.

I've created a static property that builds this info e.g.

public static class SampleInfo
{
    public static string LogoUrl
    {
        get {
                string logoUrl = "would-do-something-to-store/look-up-image-here";
                return logoUrl;
            }
    }
}

and now I can reference SampleInfo.LogoUrl and to get the URL instead of looking it up individually each time. But at the moment, this field is still passed to the view within the model, so I would still have to type Model.LogoUrl = SampleInfo.LogoUrl every time.

One thought would be to replace <img src="@Model.Logo" /> in the views with <img src="@ViewBag.Logo" /> and then set ViewBag.Logo = SampleInfo.LogoUrl; inside the base controller that all the controllers are using. It seems like most people frown on using ViewBag at all, but this seems like a very good option as it is only set in one place and if the view references @ViewBag.Logo, it will be able to automatically pull it from the base controller without any extra coding. All of the data specific to a particular view would still be passed through the strongly-typed view, just the logo would be removed from the model and placed in the ViewBag.

In this same line of thinking, I could just change the image to <img src="@SampleInfo.LogoUrl" /> and directly reference the static property, skipping the ViewBag completely.

Would skipping the ViewBag and directly referencing the static property be a fine alternative or bad/worse coding practice?

A third thought would be to add code to the base class or an action filter that would look for a particular field (e.g. Logo) within the current model and set it, if it is present. I'm not sure, however, if this is easily accomplished in a dynamic fashion?

Was it helpful?

Solution

I recommend using the format <img src="@SampleInfo.LogoUrl" />

Your views are already tied to your web site assembly so I don't see an issue with directly referencing this variable from within your views.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top