当我看员额的一个模型的回我的行动,我如何拯救回数据库,它从何而来?

StackOverflow https://stackoverflow.com/questions/2231892

  •  19-09-2019
  •  | 
  •  

我有点糊涂...

我有一个行动,需要一个ID,载荷的一个目,并将它的看法,这是必要的模型,目的类型。

经过编辑的数据形式提供的来看,我回到另一个行动接受的一个目的是同一确切类型的模式。

然而在这一点上我不能就叫库。保存,我想我有一个全新的对象现在不再与一个从原始数据库中查询,这是送给图。

所以我怎么可以更新先前的查询对象和保存的变化的数据库,而不是获得一个新的对象回来的?

我甚至试图获得一个新的象的实例数据库和分配图返回的对象,然后回购。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 });
}
有帮助吗?

解决方案

尝试使用 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 });
}

高温高剪,
查尔斯

Ps。一般来说它是一个坏主意,据绑定你域模型...使用演示模型,而不是然后你可以得到围绕这个问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top