2016-08-18 79 views
1

這是我遇到的問題的簡化版本。基本上,Visual Studio不會讓我在控制器內部創建一個對象(如列表)。創建列表時無法從控制器返回視圖

using System.Collections.Generic; 
using System.Web.Mvc; 

namespace HDDTest0818.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ViewResult Index() 
     { 
      public List<string> someList = new List<string>(); 

      return View(); 
     } 
    } 
} 

下面是我得到的錯誤:

Index - HomeController.Index();: not all code paths return a value

第三個開括號 - } expected

return - Invalid token 'return' in class, struct, or interface member declaration

View - 'HomeController.View' must declare a body because it is not marked abstract, extern, or partial

View - 'HomeController.View' hides inherited member 'Controller.View'. Use the new keyword if hiding was intended

View - Method must have a return type

最後收花括號 - Type or namespace definition, or end-of-file expected

+0

這些都是編譯時錯誤,你有無效的C#代碼。 – Louis

+1

'public List someList = new List ();' - >'List someList = new List ();' –

+0

啊,謝謝你螞蟻P!這工作!爲什麼不能公開呢? –

回答

2

你需要修改你的代碼:

using System.Collections.Generic; 
using System.Web.Mvc; 

namespace HDDTest0818.Controllers 
{ 
    public class HomeController : Controller 
    { 
     //here is where you would declare your List variable public so that scope of this variable can be within the entire class... 
     // public List<string> someList = new List<string>(); 
     public ViewResult Index() 
     { 
      /*public*/ List<string> someList = new List<string>(); 
      //you need to get rid of public before you create your List variable 
      // if you want to declare this list variable as public you need to do it outside of the method (Index()).. 

      return View(); 
     } 
    } 
} 

讓我知道,如果這有助於!

+0

這非常有幫助!謝謝!!! –

+1

@TaylorLiss不客氣。很高興我能幫上忙! –