简体   繁体   中英

sending integer value from controller to view in asp.net mvc

i am trying to send integer value from controller to view and display in view multiplied by 0.2

here the code in controller

public ActionResult Details()
    {

        ViewBag["salary"] = 1400;
        return View();
    }

and the code in view

@{
Layout = null;


   int Salary=int.Parse(@ViewBag["salary"]);
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Details</title>
</head>
<body>
    <div>
        <p> Salary: </p>
        @(Salary / 0.2)
    </div>
</body>
</html>

but it throw an exception

An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code

Additional information: Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'

Using the ViewBag is typically considered poor practice, I'd recommend using a Model (Model-View-Controller). I'll also mention that adding logic in the view is also poor practice, your logic should be controlled by the Controller.

Model

public class DetailsVM
{
  public decimal Salary { get; set ; }
}

Controller (method)

public ActionResult Details()
{
    var model = new DetailsVM();
    model.Salary = 1400 / 0.2;
    return View(model);
}

View

@model DetailsVM
@{
  Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Details</title>
</head>
<body>
<div>
    <p> Salary: </p>
    @Model.Salary
</div>
</body>
</html>

Use this code in your controller:

ViewBag.salary = 1400;

And this code in your view:

int Salary=(int)ViewBag.salary;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM