ASPForums.Net RSS Feed additions to the content that appears on ASPForums.Net(c) 2019 All rights reserved.Display dynamic Columns from database in ASP.Net MVC<p>Hi&nbsp;jon,</p> <p>There is no need to create&nbsp;viewModel. You can pass DataSet as model for the view.</p> <p>Then using loop you can display the result set in the view.</p> <p>For more details refer below article.</p> <h1 class="header"><a title="Display (Show) DataSets and DataTables in View in ASP.Net MVC Razor'a" href="">Display (Show) DataSets and DataTables in View in ASP.Net MVC Razor</a></h1> <p>Check this example. Now please take its reference and correct your code.</p> <p><strong><span style="text-decoration: underline;">Database</span></strong></p> <p>For this example I have used of Northwind database that you can download using the link given below.</p> <p><a href="" target="_blank">Download Northwind Database</a></p> <p><strong><span style="text-decoration: underline;">Namespaces </span></strong></p> <pre class="brush: csharp">using System.Configuration; using System.Data; using System.Data.SqlClient;</pre> <p><strong><span style="text-decoration: underline;">Controller</span></strong></p> <pre class="brush: csharp">public class HomeController : Controller { // GET: /Home/ public ActionResult Index() { DataSet ds = new DataSet(); string constr = ConfigurationManager.ConnectionStrings[&#34;constr&#34;].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { string query = &#34;SELECT TOP 10 CustomerID,ContactName,City,Country FROM Customers&#34;; using (SqlCommand cmd = new SqlCommand(query)) { cmd.Connection = con; using (SqlDataAdapter sda = new SqlDataAdapter(cmd)) { sda.Fill(ds); } } } return View(ds); } }</pre> <p><strong><span style="text-decoration: underline;">View</span></strong></p> <pre class="brush: html">&lt;%@ Page Language=&#34;C#&#34; Inherits=&#34;System.Web.Mvc.ViewPage&lt;System.Data.DataSet&gt;&#34; %&gt; &lt;%@ Import Namespace=&#34;System.Data&#34; %&gt; &lt;!DOCTYPE html PUBLIC &#34;-//W3C//DTD XHTML 1.0 Transitional//EN&#34; &#34;;&gt; &lt;html xmlns=&#34;;&gt; &lt;head runat=&#34;server&#34;&gt; &lt;title&gt;Index&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;% foreach (DataColumn column in Model.Tables[0].Columns) {%&gt; &lt;th&gt;&lt;%=column.ColumnName%&gt;&lt;/th&gt; &lt;% }%&gt; &lt;/tr&gt; &lt;% foreach (DataRow row in Model.Tables[0].Rows) {%&gt; &lt;tr&gt; &lt;%foreach (DataColumn column in Model.Tables[0].Columns) {%&gt; &lt;td&gt;&lt;%=row[column.ColumnName]%&gt;&lt;/td&gt; &lt;%} %&gt; &lt;/tr&gt; &lt;% }%&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt;</pre> <p><strong><span style="text-decoration: underline;">Screenshot</span></strong></p> <p><strong><span style="text-decoration: underline;"><img src="" alt="" width="399" height="386" /></span></strong></p>, 05 Jul 2019 05:28:12 GMT