Reputation: 124
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'
Upvotes: 0
Views: 14057
Reputation: 54618
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>
Upvotes: 3
Reputation: 5144
Use this code in your controller:
ViewBag.salary = 1400;
And this code in your view:
int Salary=(int)ViewBag.salary;
Upvotes: 3