How to Implemented Bind Records in MVC4 using Sqlserver From Controller to View


In this Article, I am going to explain about How to Implemented Bind Records in MVC4 using Sqlserver From Controller. I have Implemented Bind Records in MVC4 using Sqlserver From Controller Passing list from Controller to View . I have post source which is given below.

How to Implemented Bind Records in MVC4 using Sqlserver From Controller to View


How to Create MVC4 Project and Select View for aspx.I have attached snapshots given below. We need Design view like this . We can use Html table for bind the record using list object


<h1>How to Bind Records using Html Table From C# - Controller.</h1>
<table>
<tr>
<th>
<%: Html.DisplayNameFor(model => model.EmpId) %>
</th>
<th>
<%: Html.DisplayNameFor(model => model.EmpNo) %>
</th>
<th>
<%: Html.DisplayNameFor(model => model.EmpName) %>
</th>
<th></th>
</tr>

<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.DisplayFor(modelItem => item.EmpId) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.EmpNo) %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.EmpName) %>
</td>
<td>
<%: Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %> |
<%: Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) %> |
<%: Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }) %>
</td>
</tr>
<% } %>

</table>

How to Establish the connection and Fetch Records from database and Fill data Sqladapter then
using loop assign the each row records to list object pass the list from Controller to View


SqlConnection sqlcon = new SqlConnection("Data source=PC-NAME;Initial Catalog=Test;Integrated security=True;");
SqlDataAdapter sqladp;
DataTable dt = new DataTable();
List lstemp = new List();
public ActionResult Index()
{
sqladp = new SqlDataAdapter("Select * from TblEmp", sqlcon);
sqladp.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
lstemp.Add(new Employee() { EmpId =int.Parse(dr[0].ToString()),EmpName=dr[1].ToString(),EmpNo=dr[2].ToString()});
}
return View(lstemp);
}


Attachments

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: