我想在视图中显示我的表数据(MVC)

时间:2017-09-10 08:27:39

标签: asp.net-mvc asp.net-mvc-4 oracle-sqldeveloper

这是我的操作方法,Model类和View,当我运行代码时出现错误:foreach语句不能对类型为'login.Models.Member1'的变量进行操作,因为'login.Models.Member1'不包含公共定义为'GetEnumerator。请帮帮我!!

public ActionResult Details(Member1 mem)
{
    var name = mem.Name;
    var age = mem.Age;
    var sex = mem.Sex;
    var fees = mem.Fees;
    OracleConnection connection = new OracleConnection();
    connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionDHC"].ToString();
    connection.Open();
    OracleCommand command = connection.CreateCommand();
    string sql = "SELECT * FROM MEMBER";
    command.CommandText = sql;
    return View();
}

我的模特:

public class Member1
{
    public String Name { get; set; }
    public String Age { get; set; }
    public String Sex { get; set; }
    public String Fees { get; set; }
}

查看:

@model login.Models.Member1

@{
    ViewBag.Title = "Details";
    Layout = null;
}
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Sex</th>
            <th>Fees</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.Name</td>
                <td>@item.Age</td>
                <td>@item.Sex</td>
                <td>@item.Fees</td>
            </tr>
        }
    </tbody>   
</table>

1 个答案:

答案 0 :(得分:0)

你犯了错误。 首先需要执行命令并初始化它;

var result = command.executeNonQuery()或command.executeReader()//这是我用过的年龄

比使用此

将其返回给您查看

返回View(var);

所以我建议的更改是`

public ActionResult Details(Member1 mem)
{
    var name = mem.Name;
    var age = mem.Age;
    var sex = mem.Sex;
    var fees = mem.Fees;
    OracleConnection connection = new OracleConnection();
    connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionDHC"].ToString();
    connection.Open();
    OracleCommand command = connection.CreateCommand();
    string sql = "SELECT * FROM MEMBER";
    command.CommandText = sql;
    var result = command.executeNonQuery() //or reader just make sure you 
    //make sure you get result in result variable
    // than send it to view
    return View(result);
}

一切都很好