Anthony Gorshenin Anthony Gorshenin - 7 months ago 20
ASP.NET (C#) Question

Interaction of data between View and Controller

My Controller function and variable "money"

static int? money = 500;

public ActionResult SubmitPurchase(int? orderPrice)
money = money - orderPrice;

ViewBag.Money = money;

if (db.Purchases.Any())
db.Database.ExecuteSqlCommand("delete from PurchaseLists");
return View();
else return RedirectToAction("Order");

My View

<div align="center">
<p><h1>Thank you!</h1></p>
<p><h2>Your balance is @ViewBag.Money</h2></p>
<p><h2>Come again plz! :)</h2></p>
<a href="/Home/Order">
<input type="button" value="main menu"/>

Another view sends by URL value
in function
. My problem is that
in My View dosen't shown, but should show value of variable
after calculating in function
. What I do wrong?


If you are not passing a valid integer value to the orderPrice parameter, your code will try to execute 500-null which results in null and null value will be stored in money variable and will be set to ViewBag.

You can do a null check before doing the maths to prevent this happening.

    money = money - orderPrice;

The url you are trying to access is http://localhost:61314/Home/SubmitPurchase/49 . With the default MVC route registration, It will not map to the orderPrice parameter of your method. You can either update the code to have the url to be generated like


Or update your action method parameter name to be id

 public ActionResult SubmitPurchase(int? id)
        money = money - id;
     // do something
    return View();

Assuming your SubmitPurchaseview (SubmitPurchase.cshtml) has the code to read the ViewBag item and display it.