扩展方法和ViewModels是在前端扩展数据层对象的标准方法,如下所示:
数据层(类库,Person.cs):
namespace MyProject.Data.BusinessObjects
{
public class Person
{
public string Name {get; set;}
public string Surname {get; set;}
public string Details {get; set;}
}
}
显示层(Web应用程序)PersonExtensions.cs:
using Data.BusinessObjects
namespace MyProject.Admin.Extensions
{
public static class PersonExtensions
{
public static HtmlString GetFormattedName(this Person person)
{
return new HtmlString(person.Name + " <b>" + person.Surname</b>);
}
}
}
ViewModel(用于特定于扩展视图的数据):
using Data.BusinessObjects
namespace MyProject.Admin.ViewModels
{
public static class PersonViewModel
{
public Person Data {get; set;}
public Dictionary<string,string> MetaData {get; set;}
[UIHint("FCKeditor")]
public object PersonDetails { get { return Data.Details; } set {Data.Details = value;} }
}
}
控制器PersonController.cs:
public ActionMethod Person(int id)
{
var model = new PersonViewModel();
model.Data = MyDataProvider.GetPersonById(id);
model.MetaData = MyDataProvider.GetPersonMetaData(id);
return View(model);
}
查看,Person.cshtml:
@using MyProject.Admin.Extensions
<h1>@Model.Data.GetFormattedName()</h1>
<img src="~/Images/People/image_@(Model.MetaData["image"]).png" >
<ul>
<li>@Model.MetaData["comments"]</li>
<li>@Model.MetaData["employer_comments"]</li>
</ul>
@Html.EditorFor(m => m.PersonDetails)