After writing webforms for many years, I am trying to make the transition to MVC. I'm having trouble getting away from Datatables and understanding how to create a model class properly. The big hiccup is my datasource is a restful webservice which returns XML.
Currently I am strongly typing the view's model as a datatable. Am I giving anything up by not using a model class? Am I including to much information in the controller?
The following is just a simple application which takes a querystring value, performs a search using a restful webservice, and spits out the results on the page. It works, but I don't feel like I've created an actual MVC application.
My Controller:
using System.Web.Mvc;
using System.Data;
using System.Configuration;
namespace mvc1.Controllers
{
public class HomeController : Controller
{
dhRestful _datahandler = new dhRestful(ConfigurationManager.ConnectionStrings["service"].ConnectionString);
//
// GET: /Home/
public ActionResult Index(string search = "")
{
ViewBag.Title = "You searched for: " + search;
using (DataTable dt = _datahandler.get("tv_show?name=" + search))
{
return View(dt);
}
}
}
}
dhRestful is a helper class I ported from a previous project. It makes restful webservice calls and serializes the response XML into a DataTable. If I should continue using this class, where should I be putting it in the project files?
using System.Data;
using System.Xml;
namespace mvc1
{
public class dhRestful
{
string _hostPath = "";
public dhRestful(string hostPath)
{
_hostPath = hostPath;
}
public DataTable get(string partialUrl)
{
using (XmlTextReader xr = new XmlTextReader(_hostPath + partialUrl))
{
using (DataSet ds = new DataSet())
{
ds.ReadXml(xr);
if (ds.Tables.Count > 0)
{
return ds.Tables[0];
}
else
{
return new DataTable();
}
}
}
}
}
}
The View using razor:
@model System.Data.DataTable
<h2>@ViewBag.Title</h2>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Show Name</th>
</tr>
</thead>
<tbody>
@foreach (System.Data.DataRow row in Model.Rows)
{
<tr>
<td>@row["id"].ToString()</td>
<td>@row["name"].ToString()</td>
</tr>
}
</tbody>
</table>
Sample XML where the search was on the name "Stargate":
<myService>
<tv_show>
<id>72449</id>
<name>Stargate SG-1 </name>
</tv_show>
<tv_show>
<id>83237</id>
<name>Stargate Universe </name>
</tv_show>
<tv_show>
<id>70852</id>
<name>Stargate: Infinity </name>
</tv_show>
<tv_show>
<id>70851</id>
<name>Stargate Atlantis </name>
</tv_show>
</myService>