내 뷰가 내 행동에 모델을 다시 게시하면 어떻게 된 데이터베이스에 다시 저장합니까?
-
19-09-2019 - |
문제
난 혼란스러워 ...
ID를 취하고 객체를로드하고 해당 객체 유형의 모델에 바인딩되는보기로 전달하는 한 가지 동작이 있습니다.
View가 제공 한 양식으로 데이터를 편집 한 후 모델과 동일한 유형의 객체를 수용하는 다른 동작에 다시 게시합니다.
그러나이 시점에서 저장소를 호출 할 수는 없습니다 .Save는 지금 새로운 객체를 가지고 있다고 생각합니다. 더 이상보기로 전송 된 원래 데이터베이스 쿼리의 객체와 관련이 없습니다.
그렇다면 이전에 쿼리 된 객체를 업데이트하고보기에서 새 개체를 다시 가져 오는 대신 DB로 변경 사항을 저장하려면 어떻게해야합니까?
심지어 DB에서 객체의 새 인스턴스를 얻고 뷰를 반환 한 객체를 할당 한 다음 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 });
}
해결책
사용해보십시오 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 });
}
hths,
찰스
추신. 일반적으로 도메인 모델에 데이터를 데이터에 데이터를 바르는 것은 나쁜 생각입니다 ... 대신 프레젠테이션 모델을 사용하면이 전체 문제를 해결할 수 있습니다.
제휴하지 않습니다 StackOverflow