2016-04-14 45 views
3

我有方法public void categoriesForm_DeleteItem(int categoryID) in public partial class Categories_View1 : System.Web.UI.Page。它仿照教程http://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/shopping-cart的方法RemoveItem進行建模。在response.redirect後返回

我的方法中包含以下代碼:

public void categoriesForm_DeleteItem(int categoryID) 
{ 
    /* some code ommited */ 
    if (c != null) 
    { 
     db.Categories.Remove(c); 
     db.SaveChanges(); 
     Response.RedirectToRoute("CategoriesList"); 
     //should I add return; here? 
    } 
    else 
    { 
     ModelState.AddModelError("NotFoundError", "Category not found."); 
     return; 
    } 
    /* code ommited */ 
} 

我應該Response.RedirectToRoute( 「CategoriesList」)之後添加return;; ?

還有一個問題......我在教程中看到,方法RemoveItem返回int,返回代碼的意圖是什麼?那個返回碼在哪裏有用?

+0

如果該方法在'if..else'子句之後結束,則沒有。無需「返回」。如果不是,它取決於是否會有一些代碼可以清除響應或以某種方式更改(罕見)。 – haim770

+0

從你鏈接的教程中得到的那個方法的sig是'public void RemoveItem(string removeCartID,int removeProductID)',no int returned。 – DrewJordan

+0

@DrewJordan我一定看過int返回類型的其他方法。 :/ – Willmore

回答

5

我應該添加返回;在Response.RedirectToRoute(「CategoriesList」)之後; ?

這取決於您是否希望代碼返回。

首先,請注意Response.Redirect()Response.RedirectToRoute()之間的關鍵區別。前者(較舊)的方法默認放棄該線程,該線程拋出ThreadAbortException。因此,該語句之後的代碼無論如何都不會被執行。後者(較新)的方法,但是,不是。這意味着任何代碼預計執行。

鑑於這種情況,看看在你的榜樣的最後一位......

/* code ommited */ 

,如果你不從該方法返回的代碼將被執行。如果您不希望發生這種情況,則需要從方法返回或構造代碼,以便在調用Response.RedirectToRoute()後不存在其他代碼路徑。