0

I would like to calculate the time it takes for the method to run so I am trying to pass the start time, end time and elapsed time value to the view from the controller. How can I do that?

This is a controller that I am already using to pass value from a cs file so the ViewBag.Message is for that but I want to use another one to pass more values to the view.

public ActionResult Test()
        {
            var startTime = DateTime.Now;
            ViewBag.Message = _importFactory.importScanSourceProductData(CurrentTenantId, "", null, CurrentUserId);
            var endTime = DateTime.Now;
            var elapsedTime = endTime - startTime;
            ViewBag.Message = elapsedTime;
            return View();
        }

View

@model dynamic
@{
    Layout = null;
    var data = ViewBag.Message;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Test</title>

</head>
<body>
    <div>
        <h1>Import Scan Source Product Data</h1>
        <p>@data</p>
    </div>
</body>
</html>
Sami
  • 1
  • Does this answer your question? [How to pass data from controllers to view in ASP.net MVC?](https://stackoverflow.com/questions/37813060/how-to-pass-data-from-controllers-to-view-in-asp-net-mvc) – TAHA SULTAN TEMURI Jan 09 '20 at 12:28
  • You can create any number of ViewBags like `ViewBag.ElapsedTime`, `ViewBag.EndTime `, `ViewBag.StartTime` etc. – Rajesh G Jan 09 '20 at 12:30

1 Answers1

1

I would suggest if you want to pass multiple values from a controller to view you should be creating a new view model class with the list of properties defined to be passed.

Then go ahead and create an instance of that class in your controller and pass the instance in the return View();

example :

    public ActionResult Test()
            {
                var viewModel = new viewModel();
                var startTime = DateTime.Now;
                viewModel.Message = _importFactory.importScanSourceProductData(CurrentTenantId, "", null, CurrentUserId);
                var endTime = DateTime.Now;
                viewModel.EndTime =  endTime;
                var elapsedTime = endTime - startTime;
                viewModel.ElapsedTime =  elapsedTime;
                return View(viewModel);
            }

Now use this in .CSHTML Like - @viewModel.StartTime, etc