У меня есть это,
public ActionResult IndexByName(string lastName)
{
//find the name
return View("Index", myObject);
}
public ActionResult SomeOtherAction(IFormCollection collection)
{
if (collection["somekey"] == "search")
{
this.IndexByName(collection["lastname"]);
}
//other stuff in this method that I don't want to run if it says search
}
Как я могу предотвратить продолжение остальной части метода SomeOtherAction? Я хотел, чтобы приложение вернулось к просмотру («Индекс») другим методом.
SomeOtherAction вызывает Index, и я хотел, чтобы система возвращала View Index (в IndexByName) и прекращала выполнение в SomeOtherAction.
А return IndexByName("something"); этого не делает?
Я не пробовал. Я думал, что это сделает другой метод, потому что у него есть возврат View, а не "обычный" возврат.
Нет никакого «обычного» возврата, есть только то, что вы объявили в своем методе как возвращаемый тип, то есть ActionResult. View() просто создает и возвращает ViewResult, который, конечно, наследуется от ActionResult.





В C# ключевое слово return будет существовать в текущем методе и возвращать управление вызывающему методу. Из документация:
The
returnstatement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is avoidtype, thereturnstatement can be omitted.
Так, например, вы можете использовать это:
public ActionResult IndexByName(string lastName)
{
return View("Index", myObject);
}
public ActionResult SomeOtherAction(IFormCollection collection)
{
if (collection["somekey"] == "search")
{
// This will return the result of IndexByName()
// and exist the SomeOtherAction method
return IndexByName(collection["lastname"]);
}
else
{
// This will return the View SomeOtherView
// and exist the SomeOtherAction method
return View("SomeOtherView");
}
// In theorty this would return an HTTP 200
// but it is NEVER hit. All execution paths
// within this method resolved before we
// ever got here.
return Ok();
}
Спасибо. Я подумал, что это будет похоже на перенаправление, и я просто отправлю меня в просмотр. Нет.
Я не слежу за твоим вопросом. Они выглядят как две отдельные конечные точки, которые вообще не взаимодействуют друг с другом.