我正在构建一个非常简单的 asp.net MVC 文件上传表单。目前,我在创建在所述文件上存储信息的新数据库对象时遇到问题。
action 方法的代码如下所示:
[Authorize(Roles = "Admin")]
public ActionResult AddFile(Guid? id)
{
var org = organisationRepository.GetOrganisationByID(id.Value);
Quote newFile = new Quote();
newFile.Organisation = org;
newFile.QuotedBy = User.Identity.Name;
return View("AddFile", newFile);
}
问题是当表单回发时 newFile.Organisation 的值丢失了。我想 EF 在这个阶段没有提供 OrganisationID 的值。
[Authorize(Roles = "Admin")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddFile(Quote quote)
{
//save the file to the FS - nice!
if (ModelState.IsValid)
{
try
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/TempOrgFiles/")
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
quote.QuoteURL = file.FileName;
}
}
surveyRepository.AddQuote(quote);
surveyRepository.Save();
}
catch (Exception ex)
{
//add model state errors
ViewData["error"] = ex.Message;
}
}
return View("AddFile");
}
如果这是 linq to sql,我会简单地设置 OrganisationID,但它是 EF,这是不可能的(至少在我的设置中)
任何想法作为处理这些情况的最佳方法?(除了做一些疯狂的事情,比如为organisaionid设置一个隐藏的表单字段并在post方法中设置它)