Read Connection String from class file in ASP.Net MVC

ronaldlour
 
on Aug 07, 2022 11:56 PM
426 Views

Hi,

Need guidance from experts.

I need 4 db to be connected, how can i created this in as class file (under project structure), so that can call upon the connection string when required?

Thanks in advance

Note* Don't want to use entity framework and don't want to setup connection string in web config and beginner in MVC structure.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
KasimA
 
on Aug 08, 2022 07:32 AM

Hi ronaldlour,

Please refer below sample.

Controller

public ActionResult Submit()
{
    string con1 = DBConnection.GetConn1();
    string con2 = DBConnection.GetConn2();
    string con3 = DBConnection.GetConn3();
    string con4 = DBConnection.GetConn4();

    return View();
}

HTML

@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
{
    <input type="submit" value="Submit" />
}

DBConnection

public static class DBConnection
{
    public static string GetConn1()
    {
        return ".\\SQL2019;Initial Catalog=Northwind;Integrated Security=true";
    }

    public static string GetConn2()
    {
        return ".\\SQL2019;Initial Catalog=AjaxSamples;Integrated Security=true";
    }

    public static string GetConn3()
    {
        return ".\\SQL2019;Initial Catalog=Sample;Integrated Security=true";
    }

    public static string GetConn4()
    {
        return ".\\SQL2019;Initial Catalog=dbFiles;Integrated Security=true";
    }
}

Screenshot