在编写 Webform 多年之后,我正在尝试过渡到 MVC。我无法摆脱数据表并理解如何正确创建模型类。最大的问题是我的数据源是一个返回 XML 的静态 Web 服务。
目前,我正在将 View 的模型强键入为数据表。我是否因为不使用模型类而放弃了任何东西?我在 Controller 中包含了太多信息吗?
以下只是一个简单的应用程序,它采用查询字符串值,使用静态 Web 服务执行搜索,然后在页面上输出结果。它可以工作,但我不觉得我已经创建了一个实际的 MVC 应用程序。
我的 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 是我从之前的项目移植的一个辅助类。它进行静态 Web 服务调用并将响应 XML 序列化到 DataTable 中。如果我应该继续使用这个类,我应该把它放在项目文件的哪里?
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();
}
}
}
}
}
}
使用 Razor 的 View :
@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>
示例 XML,其中搜索名称为“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>
最佳答案
我建议您通过依赖注入(inject)在组合根编写此数据访问层。因此,稍后您可以注入(inject)满足契约(Contract)的不同客户端,而不是其余客户端。
另一个注意事项是创建 View 模型。如果您是直接在应用程序中使用的 VO 或 DTO,则最好将它们包装起来。我想这就是你的答案。您可以在模型文件夹中查看模型,也可以创建子文件夹等。
类似这样的事情:
// you need to adjust your dependency accordingly
Interface IRepository<T> : where t has a value
{
void Set(T item);
T Get(some value that you indicate in T);
}
namespace mvc1.Controllers
{
public class HomeController : Controller
{
IRepository<SomeObject> _repo;
public HomeController(IRepository<SomeObject> repository)
{
_repo = repository;
}
//
// GET: /Home/
public ActionResult Index(string search = "")
{
ViewBag.Title = "You searched for: " + search;
using (SomeObject obj = _repo.get("tv_show?name=" + search))
{
// here you can use automapper to map a DTO or VO to View model.
FooViewModel model = someobject;
return View(model);
}
}
}
}
在组合根:global.asax,您可以引导容器。方法很多,看看结构图以及如何使用容器。
关于c# - 将 M 添加到 MVC 中?从 Webforms/DataTable 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11005554/