I'm trying to create a simple site, but when I try to access a list in the index.cshtml, which I created in the index.cshtml.cs, it says it doesn't exist.
Content of the index.cshtml.cs file:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.SqlClient;
namespace Proiectss.Pages
{
public class IndexModel : PageModel
{
public List<ClientInfo> listClients = new List<ClientInfo>();
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
ViewData["listClients"] = HttpContext.Features.Get<Proiectss.Pages.Clients.IndexModel>().listClients;
}
public void OnGet()
{
try
{
String connectionString = "Data Source=.\\sqlexpress;Initial Catalog=spital;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "SELECT * FROM clients";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
ClientInfo clientInfo = new ClientInfo();
clientInfo.id = "" + reader.GetInt32(0);
clientInfo.name = reader.GetString(1);
clientInfo.email = reader.GetString(2);
clientInfo.phone = reader.GetString(3);
clientInfo.adress = reader.GetString(4);
clientInfo.created_at = reader.GetDateTime(5).ToString();
listClients.Add(clientInfo);
}
}
}
}
}
catch(Exception ex)
{
Console.WriteLine("Exception: " + ex.ToString());
}
}
}
public class ClientInfo
{
public String id;
public String name;
public string email;
public String phone;
public String adress;
public String created_at;
}
}
Content of the index.cshtml:
@page
@model Proiectss.Pages.Clients.IndexModel
@{
}
<br>
<h2>List of Clients</h2>
<a href="/Clients/Create">`New Client`</a>
ID
Name
Email
Phone
Adress
Created At
Action
@foreach (var item in Model.listClients) /* this is where I get the error */
{
@item.id
@item.name
@item.email
@item.phone
@item.adress
@item.created_at
}
I am trying to access the list, but I can't.
Within your index.cshtml, you are defining your model as
Proiectss.Pages.Clients.IndexModel, but the namespace in your index.cstml.cs isProiectss.Pages.Meaning that the model that you are using in your
cshtmlfile is not the same as the one you posted in theindex.cshtml.cs.Furthermore, you do not need this line in your 'Ctor of
IndexModelThe
OnGet()method will be called by the framework and when your used model in your razor page matches the class that you posted here, the public propertylistClientswill be filled and usable within your razor page.How it looks like to me, is that you have two
IndexModelclasses and are attempting to use the wrong one.My suggestion would be to move the
listClientsproperty andOnGet()method from theProiectss.Pages.IndexModelclass to theProiectss.Pages.Clients.IndexModelclass, then everything should work as you expect them to.