using simple queries in ASP.NET MVC

后端 未结 4 1499
遇见更好的自我
遇见更好的自我 2020-12-29 16:03

I checked google but found nothing good. I am searching for usinf Traditional SQL queries in MVC instead of Entity framework etc. So it would be go

4条回答
  •  轮回少年
    2020-12-29 16:35

    So just add a Helper class and write whatever you need (Sql connections,commands,queries...), then call these helper methods from your controller.It's not different than old style

    Static Helper Class:

    public static class HelperFunctions
    {
        private static string connString = "your connection string";
    
        public static IEnumerable GetAllUsers()
        {
            using (var conn = new SqlConnection(connString))
            using (var cmd = new SqlCommand(connection:conn))
            {
                // set your command text, execute your command 
                // get results and return
            }
        }
    

    In your Controller:

    public ActionResult Users()
        {
          // Get user list
            IEnumerable users = HelperFunctions.GetAllUsers();
    
            // Return your view and pass it to your list
            return View(users);
        }
    

    In your View set your View model:

    @model IEnumerable
    

    Then you can access your user list from your View, for example:

    foreach(var user in Model)
    {
       

    @user.Name

    }

    Model represents your actual View Model.If you want access more than one list from your View, you can use ViewBag or ViewData. Check this article for more information: http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-2cplusViewBagplusandplusTem

提交回复
热议问题