1

I would like to access the Html object inside a class, so I could call Class.Method to render something using Html.Partial.

Is there a way I can call it Class.Method() instead of Class.Method(Html) ?

1 Answer 1

1

One way or another you're going to need a reference to HtmlHelper to call the Partial method.

You can make it an extension of HtmlHelper

public static MvcHtmlString Method(this HtmlHelper helper, Class @class)
{
    return helper.Partial(....);
}

Or create an HtmlHelper from within the Method method on Class, which might be more problematic since the Context won't exist on that class unless you find a reference to it through your HttpContext

You can easily create an HtmlHelper on your Controller like so:

    HtmlHelper _htmlHelper;
    public HtmlHelper HtmlHelper
    {
        get 
        {
            if (_htmlHelper == null)
            {
                TextWriter writer = new StringWriter();
                _htmlHelper = new HtmlHelper(new ViewContext(ControllerContext,
                    new WebFormView("Default"),
                    new ViewDataDictionary(),
                    new TempDataDictionary(), writer), new ViewPage());
            }

            return _htmlHelper;
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.