c# - Retrieve all data from the database got the second row same with the first row -


this problem not appear when had combined both models , codes in same class, right separate models , codes different class. made 2 column , each 1 have different value (data).

when ran program, retrieve data database, , result got: (totally wrong)

database table (user) :

enter image description here

however, when check database ide (visual studio 2013), appears correctly:

enter image description here

here code using:

model (usercontext) :

public class usercontext     {         [display(name = "username:")]         public string username         {             get;             set;         }     } 

controller :

usermanager manager = new usermanager();  public actionresult list()         {             list<usercontext> user = manager.fetch();              return view(user);         } 

code behind (usermanager) :

public list<usercontext> fetch()         {             list<usercontext> users = new list<usercontext>();              usercontext context = new usercontext();              using (sqlconnection conn = new sqlconnection(connectionstring))             {                 string query = "select [username] [user] order [username] asc";                  conn.open();                  using (sqlcommand cmd = new sqlcommand(query, conn))                 {                     using (sqldatareader reader = cmd.executereader())                     {                         while (reader.read())                         {                             context.username = reader["username"].tostring();                              users.add(context);                         }                     }                 }             }              return users;         } 

view (list view) :

@model  list<project_name.models.usercontext>  @{     viewbag.title = "user list"; }  <h2>user list</h2> <br />  <table id="example" class="display" cellspacing="0" width="100%">     <thead>         <tr>             <th>                 username             </th>         </tr>     </thead>      <tbody>         @foreach (var item in model)         {             <tr>                 <td>                     @html.label(item.username)                 </td>             </tr>         }     </tbody> </table> 

is problem because put usermanager class outside models folder, , usercontext inside models folder?

thank much.

your answer appreciated.

your error occurs because declare 1 instance of context, , keep updating username in while loop (inside while loop add reference of collection)

you need declare new instance inside loop

while (reader.read()) {   usercontext context = new usercontext();   context.username = reader["username"].tostring();   users.add(context); } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -