Bineesh Viswanath

Bineesh Viswanath

  • 1.3k
  • 424
  • 43.3k

How to display DataTable value in View in MVC

Aug 23 2019 4:48 AM
Hello All,
 
I am new to MVC architecture. I am facing an issue in loading value from database in mvc view page.
I using MS sql server as backend and stored procedure to call value into controller action.
This is my view code to trigger the data retreive function
<h2>ShowSearchOptions</h2>
@using (Html.BeginForm("GetStudentList", "Register"))
{
@Html.AntiForgeryToken()
And the Controller action :-
public ActionResult GetStudentList(StudentRegistration regObj)
{
DataTable table = new DataTable();
using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["SCHLERP"].ToString()))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("GetStudentDetails", sqlCon))
{
adapter.SelectCommand.Parameters.Add("@FULLNAME", SqlDbType.NVarChar).Value = regObj.FULLNAME;
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
return View(table);
}
}
}
return View();
}
And the View page to display the data :-
@model SchoolERP.Models.StudentRegistration
@{
ViewBag.Title = "GetStudentList";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetStudentList</h2>
<div>
<h4>StudentRegistration</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.FULLNAME)
</dt>
<dd>
@Html.DisplayFor(model => model.FULLNAME)
</dd>
<dt>
@Html.DisplayNameFor(model => model.DOB)
</dt>
<dd>
@Html.DisplayFor(model => model.DOB)
</dd>
<dt>
@Html.DisplayNameFor(model => model.GENDER)
</dt>
<dd>
@Html.DisplayFor(model => model.GENDER)
</dd>
<dt>
@Html.DisplayNameFor(model => model.PARENTNAME)
</dt>
<dd>
@Html.DisplayFor(model => model.PARENTNAME)
</dd>
<dt>
@Html.DisplayNameFor(model => model.EMAIL)
</dt>
<dd>
@Html.DisplayFor(model => model.EMAIL)
</dd>
<dt>
@Html.DisplayNameFor(model => model.NATIONALITY)
</dt>
<dd>
@Html.DisplayFor(model => model.NATIONALITY)
</dd>
<dt>
@Html.DisplayNameFor(model => model.PHONENUMBER)
</dt>
<dd>
@Html.DisplayFor(model => model.PHONENUMBER)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ADDRESS)
</dt>
<dd>
@Html.DisplayFor(model => model.ADDRESS)
</dd>
<dt>
@Html.DisplayNameFor(model => model.USERNAME)
</dt>
<dd>
@Html.DisplayFor(model => model.USERNAME)
</dd>
<dt>
@Html.DisplayNameFor(model => model.PASSWORD)
</dt>
<dd>
@Html.DisplayFor(model => model.PASSWORD)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
@Html.ActionLink("Back to List", "Index")
</p>
AND an error is coming :-
Server Error in '/' Application.
The model item passed into the dictionary is of type 'System.Data.DataTable', but this dictionary requires a model item of type 'SchoolERP.Models.StudentRegistration'.

Answers (1)