Tanvi Jain

Tanvi Jain

  • 1.7k
  • 53
  • 6.6k

View without using razor syntax. How to bind model?

May 5 2021 1:19 PM
I want to build view using html/javascript/jquery and do not want to use razor syntax. How do I bind my model ? How do I iterate list in view to display rows?
 
Controller
  1. public ActionResult Index()  
  2. {  
  3. List<Employee> employeeList = new List<Employee>();  
  4. string CS = ConfigurationManager.ConnectionStrings["mvcappDbConnection"].ConnectionString;  
  5. using (SqlConnection con = new SqlConnection(CS))  
  6. {  
  7. SqlCommand cmd = new SqlCommand("SELECT * FROM Employee", con);  
  8. cmd.CommandType = CommandType.Text;  
  9. con.Open();  
  10. SqlDataReader rdr = cmd.ExecuteReader();  
  11. while (rdr.Read())  
  12. {  
  13. var employee = new Employee();  
  14. employee.EmployeeID = Convert.ToInt32(rdr["EmployeeID"]);  
  15. employee.LastName = rdr["LastName"].ToString();  
  16. employee.FirstName = rdr["FirstName"].ToString();  
  17. employeeList.Add(employee);  
  18. }  
  19. }  
  20. return View(employeeList);  
View:
  1. @{  
  2. Layout = "~/Views/Shared/_Layout.cshtml";  
  3. }  
  4. @model IEnumerable<aspnetmvc1.Models.Employee>  
  5. <!DOCTYPE html>  
  6. <html>  
  7. <head>  
  8. <title>Employee list</title>  
  9. <script>  
  10. var Employees = @Html.Raw(Json.Encode(@Model));  
  11. alert(Employees);  
  12. for (var i = 0; i < Employees.length; i++) {  
  13. alert(Employees[i].Lastname);  
  14. alert(Employees[i].Firstname);  
  15. }  
  16. </script>  
  17. </head>  
  18. <body>  
  19. <table style="width:50%">  
  20. <tr>  
  21. <th>Empployee ID</th>  
  22. <th>Lastname</th>  
  23. <th>Firstname</th>  
  24. </tr>  
  25. @*@foreach (var e in Model)  
  26. {  
  27. <tr>  
  28. <td>@e.EmployeeID</td>  
  29. <td>@e.LastName</td>  
  30. <td>@e.FirstName</td>  
  31. </tr>  
  32. }*@  
  33. </table>  
  34. </body>  
  35. </html>  

Answers (2)