Hi @phani sekhar,
Do you mean to output the corresponding table data by the name of the table without a model?
You can create SqlCommand
object(Need to reference System.Data.SqlClient
) and then use DataSet
and use SqlDataAdapter
to operate database. Below is my test code:
Controller:
public IActionResult Index()
{
return View();
}
[HttpGet]
public DataTable GetData(string Table)
{
string connectionString = "Server=(localdb)\\mssqllocaldb;Database=TestDbOne;Trusted_Connection=True;MultipleActiveResultSets=true";
SqlConnection sqlconn = new SqlConnection(connectionString);
try
{
sqlconn.Open();
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM "+Table, sqlconn);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = sqlcmd;
DataSet ds = new DataSet();
sda.Fill(ds, "table1");
DataTable dataTable = ds.Tables["table1"];
sqlconn.Close();
return dataTable;
}
Index.cshtml:
<div>
//You can create input box or selectlist to pass the table name
<button onclick="GetData('MyTable')">Click Here to Get Data!</button>
</div>
<div id="table"></div>
<script>
function GetData(value)
{
$.ajax({
type: 'Get',
url: '/Home/GetData?Table='+value,
success: function (result) {
var keys = Object.keys(result[0]);
var html = "<table class='table'><thread><tr>";
for(var key in keys)
{
html+= "<th>"+keys[key]+"</th>";
}
html+="</tr></thread><tbody>";
for(var res in result)
{
html+="<tr>";
var values = Object.values(result[res]);
for(var val in values)
{
html+= "<td>"+ values[val] +"</td>";
}
html+="</tr>";
}
html+= "</tbody></table>";
$("#table").append(html);
},
error: function () {
alert('Failed to receive the Data');
console.log('Failed ');
}
})
}
</script>
Test Result:
Is this what you want?
If the answer is helpful, please click "Accept Answer" and upvote it. Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Chen Li