Friday, December 7, 2012

grab a ConnectionString out of the Web.config like so

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
namespace MyApplication.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         string connectionString = System.Configuration.ConfigurationManager.
               ConnectionStrings["DefaultConnection"].ConnectionString;
         SqlConnection connection = new SqlConnection(@connectionString);
         SqlCommand command = new SqlCommand();
         SqlDataAdapter adapter = new SqlDataAdapter();
         DataSet dataSet = new DataSet();
         string query = "SELECT * FROM UserRole";
         command.CommandText = query;
         command.CommandType = CommandType.Text;
         command.Connection = connection;
         adapter.SelectCommand = command;
         adapter.Fill(dataSet);
         List<string> roleNames = new List<string>();
         foreach (DataRow dataRow in dataSet.Tables[0].Rows)
               roleNames.Add(dataRow[7].ToString());
         return View(roleNames);
      }
   }
}

 
 

...Bonus: I use my model like so in a view...

@model List<string>
<h2>roles out of UserRole</h2>
<ol>
   @foreach (var role in Model)
   {
      <li>@role</li>
   }
</ol>

No comments:

Post a Comment