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

And*_*ili 1 asp.net-mvc razor

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

@{ 
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/MasterPageMobile.cshtml";
}
Run Code Online (Sandbox Code Playgroud)

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

Pat*_*man 8

不,你不能.

@{ }元素内部的代码生成方法,不能包含class,enum以及其他定义.

看这个样本:

@{
    ViewBag.Title = "Home Page";
    int x = "abc";
}
Run Code Online (Sandbox Code Playgroud)

编译为:

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

    ViewBag.Title = "Home Page";
    int x = "abc";
}
Run Code Online (Sandbox Code Playgroud)

  • +1给出了很好的解释. (2认同)

Jez*_*Jez 8

您现在实际上可以在 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!");
    }
}
Run Code Online (Sandbox Code Playgroud)