gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:22:59 24 4
gpt4 key购买 nike

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

alt text

最佳答案

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

我知道原始解决方案的执行速度更快,但我认为这个解决方案要干净得多。

希望这可以帮助!

关于asp.net-mvc - 在 ASP.NET MVC 中编写表单的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com