2014-01-10 81 views
3

我有一個異步控制器實現如下的動作,我怎樣才能重定向到在ASP.Net使用任務MVC

public Task<ActionResult> UpdateUser(ProfileModel model) 
{ 
    return Task.Factory.StartNew(showMethod).ContinueWith(
     t => 
     { 
       return RedirectToAction("ViewUser","UserProfile"); 
     }); 
} 

但是我不能重定向到行動,我不斷收到錯誤,

無法隱式轉換類型,System.Threading.Taska.Task<Sytem.Web.Mvc.RedirectToRouteResult>System.Threading.Taska.Task<Sytem.Web.Mvc.ActionResult>

但是我真的想重定向到t他提到Action,我該怎麼做。

回答

3

您需要的UpdateUser動作的返回類型更改從Task<ActionResult>Task<RedirectToRouteResult>

public Task<RedirectToRouteResult> UpdateUser(ProfileModel model) 
{ 
    return Task.Factory.StartNew(showMethod).ContinueWith(
    t => { 
     return RedirectToAction("ViewUser","UserProfile"); 
    }); 
} 

或者你可以明確設置ContinueWith方法的泛型類型參數與ActionResult ,像這樣:

public Task<ActionResult> UpdateUser(ProfileModel model) 
{ 
    return Task.Factory.StartNew(showMethod).ContinueWith<ActionResult>(
    t => { 
     return RedirectToAction("ViewUser","UserProfile"); 
    }); 
} 
+1

非常感謝:)這個技巧。 – TBA

+0

我沒有一個簡單的想法。你有 –

2

使用此example

public async Task<ActionResult> Login(LoginModel model) { 
    //You would do some async work here like I was doing. 

    return RedirectToAction("Action","Controller");//The action must be async as well 
} 
public async Task<ActionResult> Action() {//This must be an async task 
    return View(); 
} 
+0

我不能使用異步關鍵字,我正在使用.NET 4.0 – TBA

+0

@TBA你想只用async? –

+0

http://codeclimber.net.nz/archive/2012/01/09/evolution-of-async-controller-asp-net-mvc.aspx –

4

對於來這裏尋找答案的人來說,.NET的更新版本使事情變得更簡單。在方法的定義中使用關鍵字async,您可以清除主體。

public async Task<ActionResult> UpdateUser(ProfileModel model) 
{ 
    return RedirectToAction("ViewUser","UserProfile"); 
} 
+0

感謝您的更新:) – TBA