Search code examples
sql-server-2008asp.net-mvc-3

Connect asp.net to SQL Server and show result on home page


I'm working on a new blog site where entries are stored in a SQL Server database. What I have a problem with right now is to link my homepage with SQL Server. I have previously managed to connect a program to the database. And now I tried to use the same code to asp.net mvc 3 website.

This class I saved in the folder models.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

namespace testingtesting.se.Models
{
    public class msSQL
    {
        public SqlDataReader postList()
        {
            string connectionString = "Server=;Database=;User Id=;Password= ";
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand com = new SqlCommand("SELECT * FROM Post", con);
            SqlDataReader reader = com.ExecuteReader();
            return reader;
        }
    }
}

I am new to the asp.net mvc 3 but if I understand everything correctly, classes in models folder send and receive data from the database, while the controller sends data to the view which I am trying to do now. So far, I have tried to send the results of the method postList via the controller to the view which then displays it in neat ways. But I can't get it to work.


Solution

  • So your controller might look like:

    public ActionResult Index()
    {
        msSQL mssql = new msSQL();
        return View(mssql.postList());
    }
    

    And your view might look like:

    @model SqlDataReader
    
    @while(Model.read())
    {
        Model["columnName"]
    }
    

    However, best practice would be to create a Model that represents the data you are trying to pull from your database, populate the model, and pass this Model to the view, instead of passing the SqlDataReader to the view.

    If this does not help, please post what errors you are getting/why it is not working.