So my knowledge is progressing and I'm at the stage now where I'm trying to DRY my Razor views and could use some advice.
Background: I've got a bunch of nodes (let's call them blog posts) where the editor can set a date or leave it blank. If the editor specifies a date, then I output that in the view, otherwise I make use of the CreateDate property.
Here's the little snippet I'm using to do that:
var postDate = post.HasValue("postDate")
? post.GetPropertyValue<DateTime>("postDate")
: post.CreateDate;
I'm using this little snippet all over the place now and so it seem a good candidate for abstracting into its own helper function somewhere. My question is: what would be the best way to do this? Razor helper or some other means? I want to end up being able to do something like this:
var postDate = getPostDate(post, "postDate");
Presumably then I'd be able to use it in situations like this:
Abstracting a small function
Hey gang,
So my knowledge is progressing and I'm at the stage now where I'm trying to DRY my Razor views and could use some advice.
Background: I've got a bunch of nodes (let's call them blog posts) where the editor can set a date or leave it blank. If the editor specifies a date, then I output that in the view, otherwise I make use of the CreateDate property.
Here's the little snippet I'm using to do that:
I'm using this little snippet all over the place now and so it seem a good candidate for abstracting into its own helper function somewhere. My question is: what would be the best way to do this? Razor helper or some other means? I want to end up being able to do something like this:
Presumably then I'd be able to use it in situations like this:
It seems a pretty trivial thing, but don't know where to start looking. :)
Many thanks in advance!
Charles
Hi Charles,
I would create a extension method for it.
Something like this :
Than you can do :
Dave
That's awesome, Dave, thanks so much. Just what I am looking for.
One further question, though: where exactly do I put this code in my solution?
Thanks again.
Charles
If you have a VS Solution that you compile ? Than you can put it where you want.
Otherwise putting it in the App_Code folder should work
Dave
Yes, I do have a VS solution. Is there any recommend place to put it in? Some sort of convention generally used?
I normally put it in a folder called extension methods.
Dave
Great, thanks very much!
is working on a reply...