我可以将一个枚举定义为Razor视图吗?

时间:2014-06-24 09:35:13

标签: asp.net-mvc razor

进入C#.cshtml视图我有以下代码定义了一个C#代码片段:

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

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

2 个答案:

答案 0 :(得分:8)

不,你不能。

@{ }元素中的代码会生成方法,这些方法不能包含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 :(得分:1)

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

@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!");
    }
}