如何使用实体框架DF上的存储过程填充DataTable

时间:2018-05-08 15:50:32

标签: asp.net asp.net-mvc

我有一个存储过程GetAllUsers,它返回表Users中的所有列。

以下是我想要实现的DataTable示例。

enter image description here

我正在使用Entity Framework(数据库优先)。

存储过程

ALTER PROCEDURE [dbo].[GetAllUsers]
AS
BEGIN

      SELECT * FROM Users
END

控制器

    public ActionResult Index()
    {
        // Create ViewModel/ResourcViewModel instance
        var vm = new ResourceViewModel();

       // Code to fetch data from Stored Procedure and display to DataTable
    }

查看模型

public class ResourceViewModel
{
    // Dropdown Properties
    public int UserID { set; get; }
    public string FirstName { set; get; }
    public string LastName { set; get; }
}

查看

<table class="table" id="dataTable">
    <thead>
        <tr>
           <th class="text-center">First Name</th>
           <th class="text-center">Last Name</th>
           <th class="text-center">Actions</th>

       </tr>
   </thead>
   <tbody>
    <tr>
        <td>John</td>
        <td>Wick</td>
        <td><button class="btn btn-xs btn-primary" data-toggle="modal" data-target="#exampleModal">iew Details</button>
        </td>
    </tr>

    <tr>
        <td>Black</td>
        <td>Panther</td>
        <td><button class="btn btn-xs btn-primary" data-toggle="modal" data-target="#exampleModal">View Details</button>
        </td>
    </tr>
</tbody>
</table>

我已将用户列表显示到DataTable中。我想将UserID绑定到我的View Details按钮。

1 个答案:

答案 0 :(得分:0)

1.从EF

中调用存储过程
public ActionResult Index()
{
    using (DBContext dbContext = new DBContext())
    {
         // Code to fetch data from Stored Procedure
         var vm = dbContext.[YourStoredProcedureName].Select(new ResourceViewModel(){... set values here}).ToList();
         return view(vm);
    }        
}
  1. 绑定UserID

    @model IEnumerable<ResourceViewModel>
      <table>
        <tr>           
            //set th
        </tr>    
        @foreach (var item in Model)
        {
            <tr>
                //set td
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id })//here you can change it to ViewDetails action link
                </td>
            </tr>
        }
    </table>