0

我有点困惑...

我有一个动作,它需要一个 ID,加载一个对象,然后将它传递给绑定到该对象类型的模型的视图。

在视图提供的表单中编辑数据后,我 POST 回另一个操作,该操作接受与模型完全相同类型的对象。

但是此时我不能只调用 Repository.Save,我想我现在有一个全新的对象,不再与发送到视图的原始数据库查询中的对象相关联。

那么如何更新先前查询的对象并将更改保存到数据库而不是从视图中获取新对象呢?

我什至尝试从数据库中获取对象的新实例并将返回的视图对象分配给它,然后是 Repo.Save(),仍然没有这样的运气。

我在这里做错了什么?

控制器代码:

[Authorize]
public ActionResult EditCompany(int id)
{
    //If user is not in Sys Admins table, don't let them proceed
    if (!userRepository.IsUserSystemAdmin(user.UserID))
    {
        return View("NotAuthorized");
    }

    Company editThisCompany = companyRepository.getCompanyByID(id);

    if (editThisCompany == null)
    {
        RedirectToAction("Companies", new { id = 1 });
    }

    if (TempData["Notify"] != null)
    {
        ViewData["Notify"] = TempData["Notify"];
    }

    return View(editThisCompany);
}

//
// POST: /System/EditCompany

[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditCompany(Company company)
{
    string errorResponse = "";

    if (!isCompanyValid(company, ref errorResponse))
    {
        TempData["Notify"] = errorResponse;
        return RedirectToAction("EditCompany", new { id = company.CompanyID });
    }
    else
    {
        Company updateCompany = companyRepository.getCompanyByID(company.CompanyID);
        updateCompany = company;
        companyRepository.Save();
        return RedirectToAction("EditCompany", new { id = company.CompanyID });
    }


    return RedirectToAction("Companies", new { id = 1 });
}
4

1 回答 1

0

尝试使用该TryUpdateModel方法。这样,您可以在将数据绑定到存储库之前从存储库中获取公司。

[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditCompany(int id, FormCollection form)
{
    //Default to a new company
    var company = new Company();

    //If we have an id, we must be editing a company so get it from the repo
    if (id > 0)
        company = companyRepository.getCompanyByID(id);

    //Update the company with the values from post
    if (TryUpdateModel(company, form.ToValueProvider()))
    {
        string errorResponse = "";

        if (!isCompanyValid(company, ref errorResponse))
        {
            TempData["Notify"] = errorResponse;
            return RedirectToAction("EditCompany", new { id = company.CompanyID });
        }
        else
        {
            companyRepository.Save();
            return RedirectToAction("EditCompany", new { id = company.CompanyID });
        }
    }

    return RedirectToAction("Companies", new { id = 1 });
}

HTH,
查尔斯

附言。通常,将数据绑定到您的域模型是一个坏主意……请改用表示模型,然后您就可以解决整个问题。

于 2010-02-09T20:44:01.587 回答