I am still in the process of learning the ASP.NET MVC3 Razor engine, and I’m trying to wrap my head around how to accomplish something that seems so incredibly simple.
I have a static class that encapsulates a method which calls a third party API. My _Layout.cshtml master page calls the static class, e.g.
if(@Rf.Models.PageContent.GetSomething().IsSomethingHappening) {
<span>@Rf.Models.PageContent.GetSomething().Name</span>
}
As you can see I am duplicating effort (and a call to the third party API) from my static class PageContent, method GetSomething — which returns a class.
In regular old MVC2, I would have done something like this:
<% var obj = Rf.Models.PageContent.GetSomething();
if(obj.IsSomethingHappening) { %>
<span><%=obj.Name%></span>
<% } %>
…which doesn’t duplicate effort.
I want to call PageContent.GetSomething() once, store it, and reference it if my flag is true. I do not want to call PageContent.GetSomething() again, if my flag is true.
This may be a very simple question, but I’m a bit stuck on how to accomplish it. How can I duplicate the same kind of functionality from within the Razor engine?
The equivalent in Razor would be:
Obviously having views to pull data from static methods is one of the ugliest and anti-MVC practice. Views shouldn’t pull any data. They should only use data that was provided to them by the controller.
So here’s the correct way to do this:
and in the corresponding view (
~/Views/Foo/Index.cshtml):and to call this from your
_Layoutsimply: