假设我有一个Web应用程序,对于某些数据库表,我想将其数据作为数组/对象集合返回以显示在网页中,并以json为例来构建api。
我的问题是:我应该在我的模型中创建一个方法来从数据库返回数据作为json和其他方法将数据作为数组返回,或者我应该只使用“getData”方法并且他们操纵我的输出控制器?
案例1:
的模型: 的
function getDataFromDb(){
// query the db
// return as array/obj
}
function getDataAsJson(){
result = getDataFromDb();
// manipulate the result and return json object
}
案例2
的型号: 的
function getDataFromDb(){
// query the db
// return as array/obj
}
的控制器 的
result = getDataFromDB();
// create json data from the returned result
答案 0 :(得分:0)
Single Responsibility principle会指示您将Web界面控制器和api控制器分开。这将是一种更清洁,更易于维护的方法。但是,如果出于某种原因无法做到这一点,那么至少要分开这些方法。 “多功能”方法难以维护,使您的方法更加复杂。
答案 1 :(得分:0)
在我看来,这是控制器的工作。模型不应该知道(或关心)格式。
我个人会创建一些帮助类来将模型数据序列化为JSON。如果您在ASP.NET MVC 3上运行,则应该查看JavaScriptSerializer类。