我可以将枚举传递到控制器中以便模型绑定器绑定它吗?

发布于 2024-09-13 08:18:27 字数 244 浏览 8 评论 0原文

如果是这样,我应该如何传递参数?与枚举名称匹配的字符串可以吗?如果我传递一个与枚举项匹配的下拉框,这会很方便。

使用 这个答案,如果我在提交回数据时可以轻松绑定到枚举。

if so, how should i pass the parameter? would a string matching the enum name be ok? This would be handy if I was passing a dropdown box that matched enumerated items.

It would be useful to use a solution presented in this answer if I could just as easily bind to the enum when I submit the data back.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

煞人兵器 2024-09-20 08:18:27

是的,当有一个像这样的控制器时:

enum MyAction { Lalala }

public ActionResult Index(MyAction action) { ... }

您只需执行Index/Lalala,一切都会正常工作。

如果您需要更复杂的绑定(例如将某个字符串值映射到复杂的类),请使用类似 StructureMap

Yes, when having a controller like:

enum MyAction { Lalala }

public ActionResult Index(MyAction action) { ... }

You can just do Index/Lalala, and everything works fine.

If you need more complex binding (like mapping a certain string value to a complex class), use something like StructureMap.

天涯沦落人 2024-09-20 08:18:27

更好的是,您还可以将 Enum 作为 get 参数传递

@Html.ActionLink("Email Quote", "UnitDetails", "Journey", new { product = product.ProductTitle, button = "email" }, new { @class = "btn btn--main btn--main-orange" })

,最终得到以下 url:http://localhost:50766/UnitDetails?product=Your%20quote&button=email

接受的操作方法如下所示:

    [SessionTimeout]
    public ActionResult UnitDetails(QuoteViewModel viewModel)

QuoteViewModel 和枚举:

public class QuoteViewModel : IQuoteViewModel
{
    public QuoteViewModelProducts Products { get; set; }

    public bool HasDiscount { get; set; }

    public string Product { get; set; }

    public DetailButtonType Button { get; set; }
}

public enum DetailButtonType
{
    Buy,
    Callback,
    Email
}

我最喜欢的是,即使您以小写形式传递枚举参数和值,它也会正确映射到大写属性和值,这让我笑得很开心。

输入图片此处描述

It gets even better you can also pass Enum as get parameter

@Html.ActionLink("Email Quote", "UnitDetails", "Journey", new { product = product.ProductTitle, button = "email" }, new { @class = "btn btn--main btn--main-orange" })

that ends up following url: http://localhost:50766/UnitDetails?product=Your%20quote&button=email

Action method that accepts looks like this:

    [SessionTimeout]
    public ActionResult UnitDetails(QuoteViewModel viewModel)

QuoteViewModel and enum:

public class QuoteViewModel : IQuoteViewModel
{
    public QuoteViewModelProducts Products { get; set; }

    public bool HasDiscount { get; set; }

    public string Product { get; set; }

    public DetailButtonType Button { get; set; }
}

public enum DetailButtonType
{
    Buy,
    Callback,
    Email
}

What I love most is even if you pass enum parameter and value as lowercase it maps correctly to Uppercase property and Value, which makes my grin profusely.

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文