解决方法:无法对空引用执行运行时绑定

时间:2019-06-17 06:10:32

标签: asp.net-mvc

我试图联接两个表,但是却无法对空引用执行运行时绑定。如何解决此问题。

代码:- 控制器:

     public ActionResult Index()
      {
        string query = "SELECT* FROM Student AS A INNER JOIN Demo AS B ON A.S_ID = B.S_ID ";
        List<Result> result = new List<Result>();
        using (SqlConnection connection = new SqlConnection(connectionstring))
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            command.Connection = connection;
            connection.Open();
            using (SqlDataReader sdr = command.ExecuteReader())
            {
                while (sdr.Read())
                {
                    result.Add(new Result
                    {
                        S_Name = sdr["S_Name"].ToString(),
                        S_LName = sdr["S_LName"].ToString(),
                        Status = sdr["Status"].ToString()
                });
                }
            }
            connection.Close();

        }

        return View();
    }

索引:

        <table class="table table-condensed table-hover">
    <thead>
        <tr>
            <td>S_Name</td>
            <td>S_LName</td>
            <td>Status</td>
          </tr>
    </thead>
    <tbody>
        @foreach (var per in Model.Result)
        {
            <tr>
                <td>@per.S_Name</td>
                <td>@per.S_LName</td>
                <td>@per.Status</td>
              </tr>
        }
    </tbody>
</table>

结果模型是两个表的联接模型,如何修改上面的代码

1 个答案:

答案 0 :(得分:1)

您忘记了将列表返回到视图中
此解决方案应该有效

 public ActionResult Index()
          {
            string query = "SELECT* FROM Student AS A INNER JOIN Demo AS B ON A.S_ID = B.S_ID ";
            List<Result> result = new List<Result>();
            using (SqlConnection connection = new SqlConnection(connectionstring))
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                command.Connection = connection;
                connection.Open();
                using (SqlDataReader sdr = command.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        result.Add(new Result
                        {
                            S_Name = sdr["S_Name"].ToString(),
                            S_LName = sdr["S_LName"].ToString(),
                            Status = sdr["Status"].ToString()
                    });
                    }
                }
                connection.Close();

            }

            return View(result);
        }