Is there 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))%>
I hope this makes sense. Let me know if there are any missing details that you need to assist.
BTW - any optimization tips are gladly taken on-bo开发者_运维知识库ard too.
Try adding the XML comments on the method like the following.
/// <summary>
/// The summary of my Script Extension method.
/// </summary>
/// <typeparam name="T">T is the type of Controller</typeparam>
/// <param name="html">The HTML helper.</param>
/// <param name="action">The action Method of the Controller.</param>
/// <returns></returns>
After putting the above comments on the extension method, I can see them in the IntelliSense. See the image below.
精彩评论