Extension method not working if I set controller property in Action, works in OnExecuting

Posted by Blankman on Stack Overflow See other posts from Stack Overflow or by Blankman
Published on 2010-06-08T20:01:26Z Indexed on 2010/06/08 20:02 UTC
Read the original article Hit count: 208

I have a class MyController that inherits from Controller, so all my controllers inherit from MyController.

I have a property in MyController:

public class MyController : Controller
{
    public string SomeProperty {get;set;}
}

if I set this property in MyController's OnExecuting method, my HtmlHelper extension method works fine:

public static string SomeExtension(this HtmlHelper htmlHelper)
{
    StringBuilder sb = new StringBuilder();            
        string result = "";
    var controller = htmlHelper.ViewContext.Controller as MyController;
    if (controller != null)
    {
        result = controller.SomeProperty;
    }

       return result;
}

it doesn't work if I set 'SomeProperty' in my controllers action method.

I guess because I am doing 'as MyController' in the extension method?

is there a way for it to work in both situations?

I am using the value of SomeProperty to be outputted on my view pages.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET