开发者

How to execute an SQL string directly in ASP.NET MVC 2?

A开发者_开发技巧SP.NET MVC 2 + SQL Server Express...


The same way you would in every .NET application:

using (var connection = new SqlConnection("PUT YOUR CONNECTION STRING HERE"))
using (var command = connection.CreateCommand())
{
    connection.Open();
    command.CommandText = "SELECT id FROM table";
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            // TODO: read the results
        }
    }
}


As Darin pointed out, it's the same as any other .NET application.

However, it's worth noting that it should really be done as part of an Action inside of a Controller, not directly in your view. The Web Forms way is like having the View and Controller wrapped into one object.

One of the goals of the MVC pattern is to separate your view, controller and model so the views are free to display their data without worrying about where it came from or how it got there. The controllers deal with assembling that data ready for the view to display and the models are used as the data layer populated by the controller and given to the view to display.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜