0

I'm new to ASP.NET and MVC architecture. I want to display a number in a view after doing a calculation as follows

the total is here[![]

How can I display the totalmessage in a view?

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
Tharushi Geethma
  • 1,249
  • 15
  • 21

2 Answers2

3

You can use a view model to hold your data.

public class TotalViewModel 
{
  public int Total {get; set;}

  public string Message {get; set;}
}

Then in the controller

public ActionResult Calculate()
{
  // do your calculations...

  var model = new TotalViewModel { Message = "Total = ", Total = total };

  return this.View(model);
}

And the view

@model Path.To.Your.TotalViewModel

<p>@Model.Message @Model.Total</p>
Ivan Mladenov
  • 1,787
  • 12
  • 16
0

You can use ViewBag for any data to pass view, add these code to the Calculate method you have;

ViewBag.total = totalMessage;

than in the Calculate.cshtml view;

<p>@ViewBag.total</p>

that's all

  • There are very few occasions where using a `ViewBag` over a model to pass data to a view is recommended. – Ryan Searle Aug 16 '17 at 08:53
  • @RyanSearle I think Op gonna use it in a Controller, and 'ViewBag' is the most common way to pass (single step) data to the View, cheap and useful. –  Aug 16 '17 at 12:56
  • So? i dont get what you are opposing to. Make your calculations and put it in a ViewBag. I wanted to say with "single step", Controller -> View –  Aug 17 '17 at 05:55
  • Since there is a class returning 'ActionResult', I assumed it is a controller. –  Aug 17 '17 at 06:02
  • Saves me from explaining it - https://stackoverflow.com/questions/4766062/is-using-viewbag-in-mvc-bad – Ryan Searle Aug 17 '17 at 09:39
  • 1
    Hmm interesting, I will research on this issue, thanks for sharing. I always think (as a newbie) ViewBag is easy and fast so it is good. –  Aug 17 '17 at 10:27