所以我继续创建我的 MVC 3 web 应用程序时,我突然意识到我可能在我的 Controller 中放置了太多的逻辑,它需要在模型中。问题是,在这个特定的例子中,我正在处理一个文件。
SQL 数据库表存储文件的路径,文件本身保存在一个目录中。所以在数据库中,文件路径被存储为一个 nvarchar,而在模型中,文件是一个字符串,一切都在这一点上是一致的。当需要上传文件时,问题就出现了,那时我正在处理 System.IO.File。
所以问题是,当在后端它实际上是一个字符串时,如何在模型内部为文件提供 System.IO.File 逻辑?
我已经完成了 Controller 的功能版本,其中已经有了一些逻辑,当我意识到我正在针对系统工作时,我正准备添加更多。我的意思是,为了进行服务器端验证,逻辑需要在模型中,以便输入验证按照适当的 MVC 规则运行和工作,显然可以选择结合使用客户端验证。
目前...
这是我的观点:
@model ProDevPortMVC3.Profile
@{
ViewBag.Title = "Profile Photo Upload";
}
<h2>Photo Upload</h2>
<img alt="Profile Image" src="@Html.DisplayFor(model => model.ProfilePhotoPath)" />
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("UploadPhoto", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<br />
<input type="file" name="File1" />
@Html.ValidationMessageFor(model => model.ProfilePhotoPath)
<input type="submit" value="Upload" />
}
这是我的 Controller (只是相关的操作方法):
[HttpPost]
public ActionResult UploadPhoto(int id, FormCollection form)
{
Profile profile = db.Profiles.Find(id);
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
try
{
string newFile = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/Content/users/" + User.Identity.Name + "/" + newFile));
profile.ProfilePhotoPath = "/Content/users/" + User.Identity.Name + "/" + newFile;
UpdateModel(profile);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}
这是我的模型(只是与文件相关的部分):
public string ProfilePhotoPath { get; set; }
所以我想,在这些特殊情况下,你们的解决方案是什么?
最佳答案
描述
假设我理解你的问题。我已经阅读了你的问题几次。 ;) 如果我不明白,请评论我的答案以获得更好的答案(我会更新)
我认为您想要的是.. 如何为您的特定情况进行模型验证。
您可以使用 ModelState.AddModelError("Key", "Message)
添加模型验证错误方法。
ModelState.AddModelError Adds a model error to the errors collection for the model-state dictionary.
样本
ModelState.AddModelError("ProfilePhotoName", "YourMessage");
这会影响ModelState.IsValid
所以你可以做任何你想做的事情(你的逻辑)并且可以让你的模型无效。更多信息
关于asp.net-mvc-3 - MVC 关注点分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9049825/