首页 > 解决方案 > 试图将数据字符串从控制器传递到视图

问题描述

我正在尝试将数据字符串从控制器传递到使用 viewbag 进行查看,但无法获取值

在视图端,我在控制器端的 viewbag 中收到了数组值的字符串,并希望在视图端填充表的列

控制器

 object o = command.Parameters["var_value"].Value;
 if (o != null)
 {
  string val = o.ToString();
  string[] values = val.Split('~');
  ViewBag.values = values;
}

看法

var values=@ViewBag.values as string[];
<table class="table">
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
         </tr>
        <tr>
            <td>values[1]</td>
            <td>values[2]</td>
            <td>values[3]</td>
         </tr>

预期:值应绑定在视图侧的列中实际:值未绑定在视图侧的列中

标签: c#asp.net-mvc

解决方案


将变量放在 C# 代码块中。

@{
    var values = ViewBag.values as string[];
}

<table class="table">
    <tr>
        <th>A</th>
        <th>B</th>
        <th>C</th>
     </tr>
    <tr>
        <td>@values[0]</td>
        <td>@values[1]</td>
        <td>@values[2]</td>
     </tr>

推荐阅读