asp.net - SQL Statement - Select data from database with condition - MVC4 -
i have written sql statement select data database in mvc4 .
what try select data compare value.
here mean:
@{ var db = database.open("defaultconnection"); var data = db.query("select * mag mytitle= model=>model.title"); }
i want make condition filter data.
and in html this:
<ol> @foreach (var image in data) { <li> <img src="@url.content(image.picpath)"/> </li> } </ol>
anyone knows how works?. have search lot can´t anything.
any appreciated:
first, move code out of view , put in controller. should avoid putting data access code in view because breaking mvc pattern.
second, if move code action in controller, can this:
public actionresult index() { var mymodel = getmymodel();//however var db = database.open("defaultconnection"); //don't use actual query below. exposes sql injection //use parameters instead. i'm sure db object allows use them. var data = db.query("select * mag mytitle= model='{0}'",mymoderl.title); return view("yourview", data); }
now view, can typed:
@model ienumerable<yourmodel> <ol> @foreach (var image in model) { <li> <img src="@url.content(image.picpath)"/> </li> } </ol>
finally, mentioned in code comment, don't use string concatenation build sql statements. sure whatever use access data, allows specify parameters instead.
also, never select * ...
. select columns need , no more. if column gets added table in future (for example humongous blob) retrieving column unnecessarily.
Comments
Post a Comment