create controller that returns viewmodel in csharp

To create a controller that returns a viewmodel in C#, you can follow these steps:

  1. Create a new class for your viewmodel. This class should contain all the data that you want to pass to the view.
main.cs
public class MyViewModel
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
}
110 chars
6 lines
  1. Create a new controller that inherits from the Controller class.
main.cs
public class MyController : Controller
{
    public IActionResult Index()
    {
        var viewModel = new MyViewModel
        {
            Property1 = "Hello, World!",
            Property2 = 42
        };

        return View(viewModel);
    }
}
250 chars
14 lines
  1. In the Index action of your controller, create an instance of your viewmodel and populate it with the required data.
  2. Pass the viewmodel to the View method, which returns a view that is bound to your viewmodel.
main.cs
@model MyNamespace.MyViewModel

<h1>@Model.Property1</h1>
<p>@Model.Property2</p>
82 chars
5 lines
  1. In your view, specify the type of your viewmodel using the @model directive, and access the data using the properties of your viewmodel.

gistlibby LogSnag