I have method public void categoriesForm_DeleteItem(int categoryID)
in
public partial class Categories_View1 : System.Web.UI.Page
. It is modeled after method RemoveItem
from tutorial http://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/shopping-cart .
My method contains following code:
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 */
}
Should I add return;
after Response.RedirectToRoute("CategoriesList"); ?
One more question... I saw on the tutorial that the method RemoveItem
returns int, what is the intent behind that return code? Where is that return code useful?
Redirect(), code following it will not execute. If you think about it, it would make sense not to execute it. You're basically telling your code that you want to go somewhere else. Example: Think of it as ordering a value meal at McDonalds.
When you use Response. Redirect("Default. aspx",true ) which is by default true then the execution of current page is terminated and code written after the Response.
For instance, instead of a "form" button that causes a postback and redirect, you could use a LinkButton that will behave like a hyperlink, allowing the browser to request the new page directly.
redirect() The redirect() method of the Response interface returns a Response resulting in a redirect to the specified URL. Note: This is mainly relevant to the ServiceWorker API.
Should I add return; after Response.RedirectToRoute("CategoriesList"); ?
That depends on whether or not you want the code to return.
First, note a key difference between Response.Redirect()
and Response.RedirectToRoute()
. The former (older) method by default aborts the thread, which throws a ThreadAbortException
. So no code after that statement would be expected to execute anyway. The latter (newer) method, however, does not. Which means any code after it will be expected to execute.
Given that, take a look at the last bit in your example...
/* code ommited */
That code will execute if you don't return from the method. If you don't want that to happen, you would either need to return from the method or structure the code such that no further code path exists after calling Response.RedirectToRoute()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With