3

into a C# .cshtml view I have the following code that define a C# code snippet:

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

Can I also define an enum into this section?

James
  • 77,877
  • 18
  • 158
  • 228
AndreaNobili
  • 38,251
  • 94
  • 277
  • 514
  • 1
    You should probably explain your problem a bit better and we could maybe suggest a solution, otherwise expect a lot of "no" answers. – James Jun 24 '14 at 09:46

2 Answers2

10

You actually can do this now in Razor, using the @functions section. Here's an example that works:

@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!");
    }
}
Jez
  • 26,126
  • 29
  • 119
  • 210
7

No you can't.

The code inside the @{ } elements is generated into methods, which can't contain class, enum and other definitions.

See this sample:

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

Is compiled to:

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

    ViewBag.Title = "Home Page";
    int x = "abc";
}
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306