다른 컨트롤러 작업 방법간에 데이터 전달
나는 ASP.NET MVC 4
. 한 컨트롤러에서 다른 컨트롤러로 데이터를 전달합니다. 나는이 권리를 얻지있다. 이것이 가능한지 확실하지 않습니까?
다음은 데이터를 전달하려는 소스 작업 방법입니다.
public class ServerController : Controller
{
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
// Redirect to ApplicationPool controller and pass
// updatedResultsDocument to be used in UpdateConfirmation action method
}
}
이 컨트롤러 의이 작업 메서드에 전달해야합니다.
public class ApplicationPoolController : Controller
{
public ActionResult UpdateConfirmation(XDocument xDocument)
{
// Will add implementation code
return View();
}
}
ApplicationPoolsUpdate
작업 방법 에서 다음을 시도했지만 작동하지 않습니다.
return RedirectToAction("UpdateConfirmation", "ApplicationPool", new { xDocument = updatedResultsDocument });
return RedirectToAction("UpdateConfirmation", new { controller = "ApplicationPool", xDocument = updatedResultsDocument });
어떻게 달성 할 수 있습니까?
HTTP 및 리디렉션
ASP.NET MVC의 먼저 작동 방식을 요약 해 보겠습니다.
- HTTP 요청이 들어 오면 라우트 세트와 일치합니다. 경로가 요청과 일치하면 경로에 해당하는 컨트롤러 작업이 호출됩니다.
- 작업 메서드를 호출하기 전에 ASP.NET MVC는 모델 바인딩을 수행합니다. 모델 바인딩은 기본적으로 텍스트 인 HTTP 요청의 콘텐츠를 작업 메소드의 강력한 형식 인수에 매핑하는 프로세스입니다.
또한 리디렉션이 무엇인지 스스로 상기시켜 보겠습니다.
HTTP 리디렉션은 웹 서버가 클라이언트에 보낼 수있는 응답으로 클라이언트에게 다른 URL에서 요청한 콘텐츠를 찾도록 지시합니다. 새 URL은 Location
웹 서버가 클라이언트에 반환 하는 헤더에 포함 됩니다. ASP.NET MVC에서는 RedirectResult
작업을 반환하여 HTTP 리디렉션을 수행합니다.
데이터 전달
URL 및 / 또는 정수와 같은 간단한 값을 전달하는 경우 Location
헤더 의 URL에 쿼리 변수로 많은 수 있습니다 . 이것은 다음과 같은 것을 의미합니다.
return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });
다른 사람들이 제안했듯이
이것이 작동하지 않는 이유는 XDocument
매우 복잡한 개체이기 때문입니다 . ASP.NET MVC 프레임 워크가 문서를 URL에 맞는 것이없는 화 한 다음 URL 값에서 XDocument
작업 변수로 다시 바인딩하는 간단한 방법은 없습니다 .
일반적으로 클라이언트가 다음 요청에서 서버로 다시 요청 수있는 문서를 클라이언트에 전달하는 것은 매우 쉬운 절차입니다. 모든 종류의 생성 화 및 역내 화가 필요하며 모든 종류의 문제가 있습니다. 성능에 심각한 영향을 미칠 수 있습니다.
대신, 서버에 문서를 보관하고 식별자를 클라이언트에 다시 전달하기를 원합니다. 그런 다음 클라이언트는 다음 요청과 함께 식별자를 전달하고 서버는이 식별자를 사용하여 문서를 검색합니다.
다음 요청시 검색 할 데이터 저장
이제 질문은 서버가 그 동안 문서를 어디에 저장합니까? 글쎄, 그것은 당신이 최선의 선택 시나리오에 달려 있습니다. 이 문서를 장기적으로 사용할 수 있습니다. 일시적인 정보 만 포함하는 경우 웹 서버 의 메모리 , ASP.NET 캐시 또는 Session
(또는 TempData
, Session
결국 거의 동일 함 )에 보관하는 것이 올바른 솔루션 일 수 있습니다 . 어느 쪽이든 나중에 문서를 검색 할 수있는 키 아래에 문서를 저장합니다.
int documentId = _myDocumentRepository.Save(updatedResultsDocument);
그런 다음 해당 키를 클라이언트에 반환합니다.
return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });
문서를 검색하려는 키를 기반으로 가져 오기만하면됩니다.
public ActionResult UpdateConfirmation(int id)
{
XDocument doc = _myDocumentRepository.GetById(id);
ConfirmationModel model = new ConfirmationModel(doc);
return View(model);
}
ASP.NET MVC TempData를 추천 보 ?
ASP.NET MVC TempData 사전은 컨트롤러 작업간에 데이터를 공유하는 데 사용됩니다. TempData의 값은 읽을 때까지 또는 현재 사용자의 세션 시간이 초과 될 때까지 유지됩니다. TempData의 데이터 유지는 단일 요청 이상의 값이 필요한 경우 리디렉션과 같은 시나리오에서 유용합니다.
코드는 다음과 같습니다.
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
TempData["doc"] = updatedResultsDocument;
return RedirectToAction("UpdateConfirmation");
}
그리고 ApplicationPoolController에서 :
public ActionResult UpdateConfirmation()
{
if (TempData["doc"] != null)
{
XDocument updatedResultsDocument = (XDocument) TempData["doc"];
...
return View();
}
}
개인적으로 TempData를 사용하고 싶지는 않지만 ASP.Net-MVC에서 컨트롤러 간 정보 전달에 설명 된대로 강력한 형식의 개체를 전달하는 것을 선호합니다 .
항상 명시적이고 예상되는 방법을 찾아야합니다.
나는 대신 이것을 사용하는 것을 선호합니다 TempData
public class Home1Controller : Controller
{
[HttpPost]
public ActionResult CheckBox(string date)
{
return RedirectToAction("ActionName", "Home2", new { Date =date });
}
}
그리고 다른 하나 controller Action
는
public class Home2Controller : Controller
{
[HttpPost]
Public ActionResult ActionName(string Date)
{
// do whatever with Date
return View();
}
}
너무 늦었지만 앞으로 누구에게나 도움이되기를 바랍니다.
한 컨트롤러에서 다른 컨트롤러로 데이터를 전달해야하는 경우 경로 값으로 데이터를 전달해야합니다. 둘 다 다른 요청이기 때문에 한 페이지에서 다른 페이지로 데이터를 보내는 경우 쿼리 문자열 (라우트 값과 동일)을 사용해야합니다.
하지만 한 가지 트릭을 할 수 있습니다.
호출 작업에서 호출 된 작업을 간단한 방법으로 호출합니다.
public class ServerController : Controller
{
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.
return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
// Redirect to ApplicationPool controller and pass
// updatedResultsDocument to be used in UpdateConfirmation action method
}
}
'ProgramingTip' 카테고리의 다른 글
Datatables에서 빈 데이터 메시지를 표시하는 방법 (0) | 2020.11.04 |
---|---|
Flask 서버에서 콘솔 메시지 중단 (0) | 2020.11.04 |
javascript / jquery에서 base64를 이미지로 변환 (0) | 2020.11.04 |
HTTPS / 웹 소켓에서 실행되는 Webpack Dev Server 보안 (0) | 2020.11.04 |
순환 순서이란 무엇입니까? (0) | 2020.11.04 |