6

Is there a way to open Razor component in Visual Studio with environment with dual screens . I'll love to have markup on one screen and @code {} section on other. While MVC developing usually markup is on one screen while JS is on other. Switching to Blazor C# replaces JS,But my mind is still mapped to read markup from one while is code on other. Can we create component with code separated from markp but still connected. enter image description here

adopilot
  • 4,340
  • 12
  • 65
  • 92

1 Answers1

12

You can use the code behind with a partial class :

MyComponent.razor

<h1>Thi is a component @Title</h1>

MyComponent.razor.cs

public partial class MyComponent
{
      [Parameter]
      public string Title { get; set; }
}

enter image description here

This is a 3.1 future, before 3.1 you cannot use partial class be inherits from class deriving from Microsoft.AspNetCore.Components.ComponenBase

before 3.1

MyComponent.razor

@inherits MyComponentModel
<h1>Thi is a component @Title</h1>

MyComponent.razor.cs

using Microsoft.AspNetCore.Components;

public class MyComponentModel : ComponentBase
{
      [Parameter]
      public string Title { get; set; }
}


agua from mars
  • 16,428
  • 4
  • 61
  • 70
  • Is there any convention how to set name for partial class files and where to put them in folder structure? – adopilot Jan 16 '20 at 13:38
  • Yes, it have to be named with {name of your component file razor}.cs in the same folder of your .razor file. It not required but this way your code is displayed in a collapsed node of your component in VS – agua from mars Jan 16 '20 at 13:41
  • Apologies once again, when you adding new partial class in visual studio, whic template do you using "class" or something else, because my VS won't group files in folder explorer as yours on shared picture – adopilot Jan 16 '20 at 13:55
  • 1
    I've the same issue with VS 2019 16.4.3 but not with 16.5.0 Preview 1.0. I thought it a VS settings somewhere – agua from mars Jan 16 '20 at 14:08
  • 1
    On top of Solution Explorer try to play with File nesting button and settings https://stackoverflow.com/questions/51538392/file-nesting-in-solution-explorer-of-asp-net-core-application – agua from mars Jan 16 '20 at 14:15
  • do we need manually to add code behind file? No option in VC to right click and add it? – Alexan Jan 16 '20 at 15:41
  • @Alexan yes, at the moment you need to manual add that files. It's not the default behavior. But maybe in further release who know. – agua from mars Jan 16 '20 at 15:46