How to return a DataSet to a View

前端 未结 4 423
天命终不由人
天命终不由人 2021-01-12 07:55

I am sending a standard Sql select statement to my Sql box via the SqlDataAdapter, then populating a DataSet object.

I can access the rows in the resulting DataSet,

相关标签:
4条回答
  • 2021-01-12 08:12

    If you're stuck with using DAO, I would suggest not using a DataSet and instead use a strongly typed class with the speed of SqlDataReader.GetValues() method. It's more work, but it has to be done somewhere if you want strongly typed classes which I would highly recommend.

    public class Person
    {
      public Person(Object[] values]
      {
        this.FirstName = (string)values[0];
        this.LastName = (string)values[1];
        this.Birthday = (DateTime)values[2];
        this.HasFavoriteColor = (bool)values[3];
      }
    
      public string FirstName { get; private set; }
      public string LastName { get; private set; }
      public DateTime Birthday { get; private set; }
      public bool HasFavoriteColor { get; private set; }
    }
    
    public static void DbRegressionExec()
    {
        List<Person> viewModel = new List<Person>();
    
        // SELECT TABLE CONTENTS FROM SQL !!
        RegressDB_TableList regresDB = new RegressDB_TableList();
        string sqlStr = "select
            FirstName
            ,LastName
            ,Birthday
            ,HasFavoriteColor
          from [RegressionResults].[dbo].[Diff_MasterList] 
          order by TableName";
    
        // POPULATE VIEWMODEL OBJECT
        sqlConn.Open();
    
        try
        {
          using (SqlCommand com = new SqlCommand(sqlStr, sqlConn))
          {
            using (SqlDbReader reader = com.ExecuteReader())
            {
              while(reader.Read())
              {
                viewModel.Add(new Person(com.GetValues()));
              }
            }
          }
        }
        catch (Exception e)
        {
            throw;
        }
        finally
        {
            sqlConn.Close();
        }
    
        return this.View(viewModel);
    }
    
    0 讨论(0)
  • 2021-01-12 08:18

    In your controller put the code like this

    [HttpGet]
    public ActionResult View(Modelclass viewmodel)
    {
        List<Modelclass> employees = new List<Modelclass>();
        DataSet ds = viewmodel.GetAllAuthors();
        var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Modelclass{
           AuthorId = dataRow.Field<int>("AuthorId"),
            Fname = dataRow.Field<string>("FName"),
           Lname = dataRow.Field<string>("Lname")
        });
        var list = empList.ToList();
    
    
    
        return View(list);
    }
    

    And in view

    @{
    var gd = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
        gd.Pager(WebGridPagerModes.NextPrevious);}
    @gd.GetHtml(tableStyle: "table",
    
            columns: gd.Columns(
                     gd.Column("AuthorId", "AuthorId"),
                     gd.Column("Fname", " Fname"),
                     gd.Column("Lname", "Lname", style: "description")
    
     )) 
    
    0 讨论(0)
  • 2021-01-12 08:22

    Short answer

    Directly answering your question:

    var tableList = new List<RegresDB_TableName>();
    int numRows = ds.Tables["RegresDB"].Rows.Count;
    for (int i = 0; i < numRows; i++)
    {
        string tblName = ds.Tables["RegresDB"].Rows[i].Field<string>("TableName");
        tableList.Add(new RegresDB_TableName() { TableName = tblName };
    }
    
    return View(tableList);
    

    Long answer (that's actually shorter)

    Try out dapper-dot-net.

    Your code could change to something like:

    string sqlStr = "SELECT * FROM [RegressionResults].[dbo].[Diff_MasterList] ORDER BY TableName";
    return sqlConn.Query<RegresDB_TableName>(sqlStr);
    
    0 讨论(0)
  • 2021-01-12 08:31

    Controller code

     //pQ is your query you have created 
     //P4DAL is the key name for connection string 
    
      DataSet ds = pQ.Execute(System.Configuration.ConfigurationManager.ConnectionStrings["Platform4"].ConnectionString);
    
    
      //ds will be used below
      //create your own view model according to what you want in your view 
     //VMData is my view model
    
     var _buildList = new List<VMData>();
                {
                    foreach (DataRow _row in ds.Tables[0].Rows)
                    {
                        _buildList.Add(new VMData
                        {  
         //chose what you want from the dataset results and assign it your view model fields 
    
                            clientID = Convert.ToInt16(_row[1]),
                            ClientName = _row[3].ToString(),
                            clientPhone = _row[4].ToString(),
                            bcName = _row[8].ToString(),
                            cityName = _row[5].ToString(),
                            provName = _row[6].ToString(),
                        });
    
    
    
                    }
    
                }
    
      //you will use this in your view
      ViewData["MyData"] = _buildList;
    

    View

    @if (ViewData["MyData"] != null)
    {
    
        var data = (List<VMData>)ViewData["MyData"];
        <div class="table-responsive">
            <table class="display table"  id="Results">
    
                <thead>
                    <tr>
                        <td>Name</td>
                        <td>Telephone</td>
                        <td>Category </td>
                        <td>City </td>
                        <td>Province </td>
    
                    </tr>
                </thead>
    
                <tbody>
                    @foreach (var item in data)
                    {
                <tr>
                    <td>@Html.ActionLink(item.ClientName, "_Display", new { id = item.clientID }, new { target = "_blank" })</td>
                    <td>@item.clientPhone</td>
                    <td>@item.bcName</td>
                    <td>@item.cityName</td>
                    <td>@item.provName</td>
    
                </tr>
    
                }
                </tbody>
    
    
            </table>
            </div>
            }
    
    0 讨论(0)
提交回复
热议问题