0

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'

2 Answers 2

3

Use this code in your controller:

ViewBag.salary = 1400;

And this code in your view:

int Salary=(int)ViewBag.salary;
Sign up to request clarification or add additional context in comments.

Comments

3

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.