什么是在ASP.NET MVC中编写提交数据表单的最佳方法?是像Scott Guthrie在这里演示的那样吗?是否有更好的方法?也许可以少使用字符串?
什么是在ASP.NET MVC中编写提交数据表单的最佳方法?是像Scott Guthrie在这里演示的那样吗?是否有更好的方法?也许可以少使用字符串?
我不太喜欢在我的代码中使用字符串,因为这样无法进行重构。一个好的方法是使用Linq表达式。如果你通过ViewData传递了一个模型,你可以使用以下语句:
<%= ShowDropDownBox(viewData => viewData.Name); %>
...
public static string ShowDropDownList<T>(this HtmlHelper html, Expression<Action<T>> property)
{
var body = action.Body as MethodCallExpression;
if (body == null)
throw new InvalidOperationException("Expression must be a method call.");
if (body.Object != action.Parameters[0])
throw new InvalidOperationException("Method call must target lambda argument.");
string propertyName = body.Method.Name;
string typeName = typeof(T).Name;
// now you can call the original method
html.Select(propertyName, ... );
}