Hi SUJAYS,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Follow the below steps.
1. Create you database table and insert records to it.
2. Create your MVC application.
3. In model folder add a class and name it as your database table name.
4. Add the properties with the name same as the table column name.
public class Customer
{
[Key]
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
5. Now add class and inherit it from DbContext class which is available in System.Data.Entity namespace.
6. In the default constructor inherit to base constructor to set the connection string from web config.
Then exposes DbSet properties for the types that you want to be part of the model.
public class CustomerContext : DbContext
{
public CustomerContext() : base("name=constr")
{
}
public DbSet<Customer> customersData { get; set; }
}
:base("constr") refers to the connection string in Web.config.
7. Now add the Controller and use the Context class to access the data.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
using (CustomerContext context = new CustomerContext())
{
List<Customer> customers = context.customersData.Take(5).ToList();
return View(customers);
}
}
}
8. Add View and set the value and run the project.
@model IEnumerable<Bind_TextBox_DbContext_MVC.Models.Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody>
@foreach (var customer in Model)
{
<tr>
<td>@customer.CustomerID</td>
<td>@Html.TextBoxFor(m => customer.ContactName)</td>
<td>@customer.City</td>
<td>@customer.Country</td>
</tr>
}
</tbody>
</table>
</body>
</html>
Screenshot