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
  • 80,725
  • 18
  • 167
  • 237
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 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

12

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
  • 27,951
  • 32
  • 136
  • 233
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
  • 153,850
  • 22
  • 249
  • 325