编写表单以在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,... ); }
我知道原始解决方案的执行速度更快,但我认为这个解决方案更清晰.
希望这可以帮助!