我有一个通用的IEnumerable函数,我需要在asp,net web mvc应用程序的每个控制器中使用它。我创建了一个SharedClass文件夹和一个公共类CommonMethods。
using System.Collections.Generic; using System.Web.Mvc;
namespace LearnWeb.SharedClass
{
public class CommonMethods
{
public IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
{
// Create an empty list to hold result of the operation
var selectList = new List<SelectListItem>();
// For each string in the 'elements' variable, create a new SelectListItem object
// that has both its Value and Text properties set to a particular value.
// This will result in MVC rendering each item as:
// <option value="State Name">State Name</option>
foreach (var element in elements)
{
selectList.Add(new SelectListItem
{
Value = element,
Text = element
});
}
return selectList;
}
}
}
我有一个控制器类StockController,我想在其中使用上述通用方法。但是我无法正确引用它。请指导。
using System.Collections.Generic;
using System.Web.Mvc;
using LearnWeb.Models;
using LearnWeb.SharedClass.CommonMethods;
namespace LearnWeb.Controllers
{
public class StockController : Controller
{
/ GET: Stock
public ActionResult Index()
{
return View();
}
public ActionResult NewStock()
{
ViewBag.Message = "Enter new stock details.";
var model = new StockModel();
model.items = GetSelectListItems(items); //trying to call the commonMethods.GetSelectListItems
return View(model);
}
}
我已将类和函数都声明为公共对象,并添加了引用,但无法在控制器类中进行链接。
关于,NewB
首先,using语句应为:
namespace LearnWeb.SharedClass;
只是名称空间。请注意,由于名称空间实际上不应包含单词class
,因此我发现名称有点不明显。不管怎么说,您的CommonMethods
类应该标记为static
:
public static class CommonMethods
并且方法自身应标记为静态:
public static IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
然后您可以在代码中这样称呼它:
model.items = CommonMethods.GetSelectListItems(items);
此行是错误的using LearnWeb.SharedClass.CommonMethods;
,应该是using LearnWeb.SharedClass