Taylor Liss Taylor Liss - 3 months ago 20
ASP.NET (C#) Question

Can't return view from controller when creating a list

This is a simplified version of the problem I'm having. Basically, Visual Studio won't let me create an object (like a list) inside of my controller.

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();
}
}
}


Here are the errors I'm getting:

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


The third open brace -
} 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


The last closing curly brace -
Type or namespace definition, or end-of-file expected

Answer

You need to revise your code:

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();
        }
    }
}

Let me know if this helps!