我正在開展一個Apsp.Net 6針對.Net6.
我有這個 ActionResult:
[Route( nameof(Recreate))]
public async Task<IActionResult> Recreate()
{
//Some code here
}
[HttpPost]
[Route( nameof(Recreate))]
public async Task<IActionResult> Recreate(StudentYearlyResultReCreateVm model)
{
//Some code here
}
現在我有另一個ActionResult這樣的描述:
[Route( nameof(RecreateWithId))]
public async Task<IActionResult> RecreateWithId(int id)
{
var result = await _studentYearlyResultRepository.GetByIdAsync( id );
var modelObj = new StudentYearlyResultReCreateVm() {StudentId = result.StudentId , AcademicYearId = result.AcademicYearId};
return RedirectToAction( nameof( Recreate ) , modelObj );
}
問題:
問題出在RecreateWithId方法上,我嘗試將操作RedirectToAction多載后多載Recreate,但我得到的只是重定向到獲取一個。
那么請問我如何重定向到Recreate?
先感謝您。
uj5u.com熱心網友回復:
一個快速的,可能很臟(?)的解決方案。
[Route( nameof(RecreateWithId))]
public async Task<IActionResult> RecreateWithId(int id)
{
var result = await _studentYearlyResultRepository.GetByIdAsync( id );
var modelObj = new StudentYearlyResultReCreateVm() {StudentId = result.StudentId , AcademicYearId = result.AcademicYearId};
return await Recreate(modelObj );
}
uj5u.com熱心網友回復:
當您使用 回傳操作時RedirectToAction,服務器會向瀏覽器回傳一個3xx 回應,并帶有Location該 URL 的標頭。瀏覽器然后繼續使用GET動詞訪問該 URL,除非您使用 Javascript 從該GETURL提交表單,否則無法更改此設定。
至于你的問題,我認為一個好的解決方案應該通過有一個服務進行處理來分離關注點:
[Route("api")]
public class ApiController
{
ApiService service;
public ApiController(ApiService service)
{
this.service = service;
}
[HttpGet, Route("")]
public async Task OnGetAsync()
{
await this.service.DoSomethingAsync();
}
[HttpPost, Route("")]
public async Task<IActionResult> OnPostAsync()
{
await this.service.DoSomethingElseAsync();
// If you call this, don't redirect or it may call DoSomethingAsync twice
await this.service.DoSomethingAsync();
return this.RedirectToAction(nameof("OnGetAsync"));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372582.html
