在ASP.NET MVC中编写表单的最佳方法是什么?
时间:2020-03-05 18:41:14 来源:igfitidea点击:
编写表单以在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, ... ); }
我知道原始解决方案的执行速度更快,但我认为这一解决方案要干净得多。
希望这可以帮助!