views:

74

answers:

0

Hello all,

I'm wondering if there's a way to make the parameters of this extension method 'intellisensible' from my view. at the moment, i can get a tooltip nudge of what the parameters (in the controller action method) are but would love to confidently intellisense type the parameter names for 'safety'. anyway, without further ado, the method, followed by the usage:

public static string Script<T>(this HtmlHelper html, 
                                Expression<Action<T>> action) where T:Controller
{
    var call = action.Body as MethodCallExpression;

    if (call != null)
    {
        // paramDic - to be used later for routevalues
        var paramDic = new Dictionary<string, object>();
        string actionName = call.Method.Name;
        var methodParams = call.Method.GetParameters();

        if (methodParams.Any())
        {
            for (int index = 0; index < methodParams.Length; index++)
            {
                ParameterInfo parameterInfo = methodParams[index]; 
                Expression expression = call.Arguments[index];
                object objValue;
                var expressionConst = expression as ConstantExpression;
                if(expressionConst!=null)
                {
                    objValue = expressionConst.Value;
                }
                else
                {
                    Expression<Func<object>> expressionConstOther = 
                        Expression.Lambda<Func<object>>(
                          Expression.Convert(expression, typeof(object)), 
                          new ParameterExpression[0]);
                    objValue = expressionConstOther.Compile()();
                }
                paramDic.Add(parameterInfo.Name, objValue);
            }
        }
        string controllerName = typeof(T).Name;
        if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            controllerName = controllerName.Remove(controllerName.Length - 10, 10);
        }

        var routeValues = new RouteValueDictionary(paramDic);
        var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
        var url = urlHelper.Action(actionName, controllerName, routeValues);

        const string linkFormat = "<script type=\"text/javascript\" src=\"{0}\"></script>";
        string link = string.Format(linkFormat, url);

        return link;
    }
    return null;
}

usage: (where FundShareholderController is my controller and x.JsFile() is an action method thereon)

<%=Html.Script<FundShareholderController>(x => x.JsFile("CreateInvestorBookingJsFile", 0))%>

hope this makes sense, let me know if there are any missing details that you need to assist.

cheers...

btw - any optimization tips gladly taken on-board too.