[Solved] SQL Statement – Select data from database with condition – MVC4


First, move that code out of the view and put it in the Controller. You should avoid putting Data Access code in a View because you are breaking the MVC pattern.

Second, if you move that code to an Action in your Controller, you can do this:

public ActionResult Index()
{
    var myModel = GetMyModel();//However you do it
    var db = Database.Open("DefaultConnection");
    //DON'T USE THE ACTUAL QUERY BELOW. IT EXPOSES YOU TO SQL INJECTION
    //USE PARAMETERS INSTEAD. I'm sure your db OBJECT allows you to use them. 
    var data = db.Query("SELECT * FROM Mag WHERE mytitle= model="{0}"",myModerl.Title);

    return View("YourView", data);
}

Now your view, can be strongly typed:

@model IEnumerable<YourModel> 

<ol>
     @foreach (var image in Model)
     { 
        <li>
             <img src="https://stackoverflow.com/questions/17976326/@Url.Content(image.picpath)"/>
        </li>
     }
</ol>

Finally, as I mentioned in the code comment, don’t use string concatenation to build your SQL statements. I am sure that whatever you use to access your data, allows you to specify parameters instead.

Also, never do select * from .... Select only the columns you need and no more. If a column gets added to that table in the future (for example a humongous BLOB) you will be retrieving that column also unnecessarily.

solved SQL Statement – Select data from database with condition – MVC4