Posts Tagged ‘C#’
I have been studying ASP.net MVC for a few months and with the release of MVC 2 preview 1 I have decided to jump in.
But first I wanted to check on something. With MVC using the Web Forms view engine you get a return to spaghetti code, along with a few helper classes. But to be honest, if I can avoid writing out decision simple logic structures in views such as “if/then’ I would do so. Now is classic asp this is for the most part impossible, but I think I may have stumbled on how to do this with anonymous delegates.
To use an anonymous delegate first you have to have a delegate. In this case, the delegate I have is for a model, so I’ll show you both:
Nothing really special. The delegate is a generic and can take any type to pass in an model parameter. And our model is really simple, just a simple test object with two properties.
Now let’s get to the heart of the matter. The first thing I did was just to add a method to the Home controller.
This simple methods just makes a TestModel instance and returns a Strong Type view, passing the test object. Here’s the view:
Okay. The anonymous delegate signature is simple ‘TestTemplate<TestModel> holder = delegate(TestModel Model)’. This will create a ‘holder’ object that can be passed around just like any other object. The important thing is just like with normal C# you cannot use an anonymous delegate until it has been declared. After the delegate signature comes the body that contains a mix of html and and other asp.net markup. I’ve added a comment for were the delegate body ends.
Lastly, a simple bit of view logic. Now just for testing purposes I have created a binder class (see code below) that has a static method that actually invokes the delegate, but I could have just written ‘holder.Invoke(this.Model)’ and that would have worked. But I wanted to demonstrate that just like any C# object this code can be passed around. Here is the code for TestTemplateBinder:
So I am thinking this could be used in templating scenarios where you may want to encapsulate the decision making logic in a helper but to want to keep the code mark on the page.