我的任务是上传文件。
class FileUploadController : Controller {
public ActionResult Index(HttpPostedFileBase postedFile) {
// When and how to validate it and return appropriate view and model data
// How to store the file in database and appropriately return view and model data
}
}
验证需要检查filename
是否已存在(数据库访问)以及是否支持file extension
(数据库访问)。
到目前为止,我的构架方式如下:
class FileUploadController : Controller {
public ActionResult Index(HttpPostedFileBase postedFile) {
FileUploadModel model=new FileUploadModel();
model.UploadedFile = postedFile;
FileUploadService service = new FileUploadService();
bool valid = service.Validate(postedFile);
if (valid) {
FileUploadViewModel viewModel = service.Save(postedFile);
return View("some_view", viewModel);
}
else {
return View("some_view", service.ViewModel);
}
}
}
public class FileUploadModel
{
public HttpPostedFileBase UploadedFile { get; set; }
}
class FileUploadViewModel {
public ModelState ModelState;
public String Filename;
}
public class FileUploadService
{
private FileUploadViewModel viewModel = new FileUploadViewModel();
public FileUploadViewModel Save(FileUploadModel fileUploadModel)
{
// here i will just save it to the database
// and return viewModel with valid state
}
public bool Validate(FileUploadModel fileUploadModel)
{
// I do the filename, size, etc validation here together with database validation if the file exists and appropriately attach errors to viewModel.ModelState so views can render the error
}
}
正如您所看到的,我的验证方法填充了viewModel.ModelState
,我的Save方法返回了新的FileUploadViewModel
。我真的无法决定如何设计它以便它可以成长。
我的问题是: - 如果添加突然更新操作并且我的服务提供更新方法,我将需要返回不同的数据作为ViewModel并且验证将是不同的,我应该创建新的ViewModel类和新的验证吗? - 我的验证是否在有效的地方进行?