0

我正在构建一个非常简单的 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方法中设置它)

4

2 回答 2

1

您可以在会话中存储 OrganisationID

[Authorize(Roles = "Admin")]
public ActionResult AddFile(Guid? id)
{
Session["OrganisationID"] = id;
}

然后将 EntityKey 设置为:

quote.OrganisationReference.EntityKey = new EntityKey("ContainerName.OrganizationSet","ID",Session["OrganisationID"])

如果您在 URL 中有组织 ID,您可以将发布功能更改为:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddFile(Quote quote,Guid?id)

并自动检索它(有足够的路由)。

您不需要在获取期间从存储库中获取组织,只需存储 ID。

于 2009-10-09T19:44:08.713 回答
0

数据丢失,因为它是无状态的。您在 GET 中的引用对象与在 POST 中传递的引用对象不同。由于 MVC 中的本机绑定(按属性名称),它仅部分水合。您需要在控制器中设置 CustomModelBinder或重新查询 Quote 对象。

于 2009-10-14T14:58:42.293 回答