0

私はちょっと混乱しています...

ID を取得し、オブジェクトをロードして、そのオブジェクトのタイプのモデルにバインドされているビューに渡すアクションが 1 つあります。

ビューによって提供されたフォームでデータを編集した後、モデルとまったく同じタイプのオブジェクトを受け入れる別のアクションに POST します。

ただし、この時点で単に Repository.Save を呼び出すことはできません。ビューに送信された元のデータベース クエリのオブジェクトとは関連付けられていない、新しいオブジェクトができたと思います。

ビューから新しいオブジェクトを取得する代わりに、以前にクエリされたオブジェクトを更新し、変更を DB に保存するにはどうすればよいでしょうか?

DB からオブジェクトの新しいインスタンスを取得し、View の返されたオブジェクトをそれに割り当ててから 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

Try using the TryUpdateModel method. This way you can get the company from the repository before you databind to it.

[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 });
}

HTHs,
Charles

Ps. generally it's a bad idea to databind to your domain models... use presentation models instead and then you can get around this whole issue.

于 2010-02-09T20:44:01.587 に答える