views:

217

answers:

2

Hi, so I'm very very far from an expert on MVC or ASP.NET. I just want to make a few simple Controllers in C# at the moment, so I have the following question;

Right now I have the connection string used by the controller, -inside- the controller itself. Which is kind of silly when there are multiple controllers using the same string. I'd like to be able to change the connection string in just one place and have it affect all controllers.

Not knowing a lot about asp.net or the 'm' and 'v' part of MVC, what would be the best (and simplest) way of going about accomplishing just this?

I'd appreciate any input on this, examples would be great too.

+1  A: 

You may add a connection string to the web.config file like this:

<configuration>
  <appSettings>
    <add key="ConnectionString"
      value="server=localhost;database=Northwind;uid=sa;password=secret;"/>
  </appSettings>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
</configuration>

and use it in your code like this:

strConnection = ConfigurationSettings.AppSettings("ConnectionString") // <-----
sqlConn = New SqlConnection(strConnection)
sqlCmd = New SqlCommand("SELECT * FROM Customers WHERE " & "(CompanyName LIKE 'A%') OR (CompanyName LIKE 'B%')", sqlConn)

Notice the first line. This example is for VB but you should be able to do the same in C#.

The example is taken from this link http://www.dotnetjohn.com/articles.aspx?articleid=3, but there are tons of them everywhere.

Hope this helps.

Fabio Milheiro
Awesome, this is my answer. Thank you :]
cc0
Just glad to help :)
Fabio Milheiro
+2  A: 

Put it in your web.config file like so:

<connectionStrings>
    <add name="ConnectionName" connectionString="TheConnectionString" providerName="System.Data.SqlClient" />
</connectionStrings>

<connectionStrings> is just a child of the root <configuration> element.

Then you can read it like:

string myConnStr = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;

HTHs, Charles

Charlino
Thank you, that's a good explanation!
cc0