【问题标题】:sending integer value from controller to view in asp.net mvc从控制器发送整数值以在 asp.net mvc 中查看
【发布时间】:2015-05-09 18:25:20
【问题描述】:

我正在尝试将整数值从控制器发送到视图并在视图中显示乘以 0.2

这里是控制器中的代码

public ActionResult Details()
    {

        ViewBag["salary"] = 1400;
        return 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>

但它会抛出异常

“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”类型的异常发生在 System.Core.dll 但未在用户代码中处理

附加信息:无法将带有 [] 的索引应用于表达式 'System.Dynamic.DynamicObject' 类型的

【问题讨论】:

    标签: c# exception razor asp.net-mvc-5


    【解决方案1】:

    在您的控制器中使用此代码:

    ViewBag.salary = 1400;
    

    你认为这段代码:

    int Salary=(int)ViewBag.salary;
    

    【讨论】:

      【解决方案2】:

      使用 ViewBag 通常被认为是不好的做法,我建议使用模型(模型-视图-控制器)。我还要提一下,在视图中添加逻辑也是不好的做法,你的逻辑应该由控制器控制。

      型号

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

      控制器(方法)

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

      查看

      @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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多