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

4

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

alt text


这主要是个人喜好问题,使用字符串会稍微提高一些性能,但对于大多数 Web 应用程序来说并不重要。 - BlackTigerX
1个回答

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, ... );
}

我知道原始解决方案的速度更快,但我认为这个解决方案更加简洁。希望这可以帮到你!

同时,我们可以使用T4MVC来摆脱Action="Update"的魔术字符串。 - Łukasz Wiatrak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接