0

I built a simple test app with one form when submitting the form the form data should be saved in database

namespace WebApplication3.Controllers
{
    public class Home-controller : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Customer customer)
        {
            // string ATNMEntities = ConfigurationManager.ConnectionStrings["ATNMEntities"].ConnectionString;
            using (SqlConnection con = new SqlConnection("data source=A3LABPCLENOVO\\SQLEXPRESS;initial catalog=ATNM;integrated security=True"))
            {
                string query = "INSERT INTO Customers(Customerid,Name, Country) VALUES(@Customerid,@Name, @Country)";
                query += " SELECT SCOPE_IDENTITY()";

                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();

                    cmd.Parameters.AddWithValue("@Customerid", customer.Customerid);
                    cmd.Parameters.AddWithValue("@Name", customer.Name);
                    cmd.Parameters.AddWithValue("@Country", customer.Country);

                    // customer.Customerid = Convert.ToInt32(cmd.ExecuteScalar());
                    con.Close();
                }
            }

            return View(customer);
        }
    }
}

Connection string:

<connectionStrings>
    <add name="ATNMEntities" 
         connectionString="metadata=res://*/Models.AdoEntityDataModel1.csdl|res://*/Models.AdoEntityDataModel1.ssdl|res://*/Models.AdoEntityDataModel1.msl;provider= System.Data.EntityClient;provider connection string=&quot;data source=A3LABPCLENOVO\SQLEXPRESS;initial catalog=ATNM;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
</connectionStrings>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
atif
  • 1
  • 2

2 Answers2

0

Your posted code:

  • uses "manual" ADO.Net style of creating a connection, command, and (lacks/commented) execution. So if your "issue" is it's not inserting to the SQLExpress defined in your connection string, then that's where you should look.

  • While your web.config sample is an Entity Framework (EF) connection that isn't even used in any of your posted code. Probably used elsewhere since it's there...

The link referenced shows how you can define your connection string(s) in web.config instead of writing out as you have in your code, as well as how to put it all together thereafter

EdSF
  • 11,753
  • 6
  • 42
  • 83
0

Add in Web.config

in Code behind

SqlConnection con = new SqlConnection(ConfigurationManger.Conectionstring["ATNMEntities"].Conectionstrings);