Search
Create DiagramView in MVC Project

After following the previous topic, you should be able to add a DiagramView component to your ASP.NET MVC (Model-View-Controller) user interface.

1. Create a DiagramView component

In HomeController.cs add a reference to the MindFusion.Diagramming.Mvc namespace:

C#  Copy Code

using MindFusion.Diagramming.Mvc;

In the body of the Index method, create a DiagramView instance and store it in the ViewBag:

C#  Copy Code

DiagramView view = new DiagramView("diagramView1");
ViewBag.DiagramView = view;

2. Render DiagramView inside a view

In Index.cshtml add a reference to the MindFusion.Diagramming.Mvc namespace:

Razor  Copy Code

@using MindFusion.Diagramming.Mvc

If you want to use tag helpers for adding MindFusion components to views, import them with the @addTagHelper directive:

Razor  Copy Code

@addTagHelper *, MindFusion.Diagramming.Mvc

Add the component by using either the DiagramView HTML helper:

Razor  Copy Code

@Html.DiagramView(
    (DiagramView)ViewBag.DiagramView,
    new { style = "width:100%; height:100%;" })

or alternatively using its Tag helper:

Razor  Copy Code

<mindfusion-diagramview
    component=(DiagramView)ViewBag.DiagramView
    style="width:100%; height:100%;">
</mindfusion-diagramview>

3. Create diagram items

You can create nodes and links programmatically either by calling Factory methods, or by instantiating objects of respective class and adding them to Items collection:

C#  Copy Code

// in controller

DiagramView view = new DiagramView("diagramView1");

var df = view.Diagram.Factory;

var node1 = df.CreateShapeNode(10, 10, 30, 30);
node1.Text = "Hello";

var node2 = df.CreateShapeNode(60, 25, 30, 30);
node2.Text = "ASP.NET MVC";

df.CreateDiagramLink(node1, node2);

ViewBag.DiagramView = view;

4. Preserve data between postbacks

The DiagramView component can preserve its data between postbacks by serializing and deserializing to JSON internally. Call the static FromRequest method
to get this functionality. You can check the request's content type to handle the initial setup of the view and its diagram.

C#  Copy Code

// read from request
DiagramView view = DiagramView.FromRequest("diagramView1", Request);

// initial setup
if (!Request.HasFormContentType)
{
     var df = view.Diagram.Factory;

     var node1 = df.CreateShapeNode(10, 10, 30, 30);
     node1.Text = "Hello";

     var node2 = df.CreateShapeNode(60, 25, 30, 30);
     node2.Text = "ASP.NET MVC";

     df.CreateDiagramLink(node1, node2);
}

ViewBag.DiagramView = view;

Browse the other sections of this help file to learn more about the functionality provided by the MindFusion.Diagramming classes, methods and properties. Follow the tutorials to learn how to populate the diagram model programmatically or create custom item types.