c# - MVC Connecting to Database and returning data -
i'm after wanting render data database page view using mvc.
my controller method follows:
public actionresult index() { string constr = configurationmanager.connectionstrings["database"].connectionstring; string query = "select top 10 keys dbo.testtable"; using (sqlconnection con = new sqlconnection(constr)) { sqlcommand cmd = new sqlcommand(query, con); con.open(); sqldatareader reader = cmd.executereader(); try { while(reader.read()) { console.writeline(string.format("{0}", reader)); } } { reader.close(); } } return view(); }
the corresponding model super simple:
public string keys{ get; set; }
i've debugged , connecting database properly. i've run sql query in database , returns results. however, when run below code -1 result value.
what i'm doing wrong?
public actionresult index() { list<string> result = new list<string>(); string constr = configurationmanager.connectionstrings["database"].connectionstring; string query = "select top 10 keys dbo.testtable"; using (sqlconnection con = new sqlconnection(constr)) { sqlcommand cmd = new sqlcommand(query, con); con.open(); sqldatareader reader = cmd.executereader(); try { while(reader.read()) { result.add(reader[0].tostring()); } } { reader.close(); } } return view(result); }
then in view:
@model ienumerable<string> <ul> @foreach (var item in model) <li>@item</li> } </ul>
Comments
Post a Comment