Is there a way to make the parameters of this extension method "intellisensible" from my view?
At the moment, I can get a hint under the hint that the parameters are (in the controller action method), but I would like to confidently IntelliSense enter the parameter names for "security". In any case, without further ado, the method followed by the use of:
public static string Script<T>(this HtmlHelper html,
Expression<Action<T>> action) where T:Controller
{
var call = action.Body as MethodCallExpression;
if (call != null)
{
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 FundShareholderControlleris my controller, and x.JsFile()is the action method.):
<%=Html.Script<FundShareholderController>(x => x.JsFile("CreateInvestorBookingJsFile", 0))%>
Hope this makes sense. Let me know if there is any missing data that you need to help.
BTW - any optimization tips are also taken on board.
source
share