在ASP.NET MVC中编写表单的最佳方法是什么?

时间:2008-08-20 19:16:01

标签: asp.net-mvc forms

在ASP.NET MVC中编写表单以提交某些数据的最佳方法是什么?它是Scott Guthrie在这里演示的吗?有更好的方法吗?也许少用字符串?

alt text

1 个答案:

答案 0 :(得分:2)

我不太喜欢我的代码中的字符串,因为它不可能重构。一个很好的方法是使用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, ... );
}

我知道原始解决方案的执行速度更快,但我认为这个解决方案更清晰。

希望这有帮助!

相关问题