【问题标题】:Can I define an enum into a Razor view? [duplicate]我可以将枚举定义到 Razor 视图中吗? [复制]
【发布时间】:2014-08-14 12:15:44
【问题描述】:

进入 C# .cshtml 视图我有以下定义 C# 代码 sn-p 的代码:

@{ 
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/MasterPageMobile.cshtml";
}

我还可以在此部分中定义enum 吗?

【问题讨论】:

  • 您可能应该更好地解释您的问题,我们可能会提出解决方案,否则会有很多“否”的答案。

标签: asp.net-mvc razor


【解决方案1】:

您现在实际上可以在 Razor 中执行此操作,使用 @functions 部分。这是一个有效的示例:

@using Web.Main.Models

@model RoomModel

@functions {
    enum PageModes {
        Create,
        Edit,
    }
}

@{
    // Based on what model we've been passed, we can determine whether we're dealing with an existing room (which
    // we'll want to edit) or a new room (which we'll want to create).
    PageModes pageMode;
    if (Model is CreateRoomModel)
    {
        pageMode = PageModes.Create;
    }
    else if (Model is EditRoomModel)
    {
        pageMode = PageModes.Edit;
    }
    else
    {
        throw new Exception("View model not recognized as valid for this page!");
    }
}

【讨论】:

  • 感谢您指出这一点。
  • 完美!谢谢。
【解决方案2】:

不,你不能。

@{ }元素内的代码生成为方法,其中不能包含classenum等定义。

查看此示例:

@{
    ViewBag.Title = "Home Page";
    int x = "abc";
}

编译为:

public override void Execute() {
    #line 1 "c:\xxx\WebApplication3\Views\Home\Index.cshtml"

    ViewBag.Title = "Home Page";
    int x = "abc";
}

【讨论】:

  • +1 很好的解释。
  • 对不起,这是不正确的。看我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 2021-06-11
相关资源
最近更新 更多