我在〜/ Helpers / Helpers.cs中有以下内容:
namespace AdjusterSave.Helpers
{
public class Helpers : Controller
{
// various methods such as the following...
public void GetDropdowns()
{
}
}
}
我试图在我的〜/ Controllers / AdjusterController.cs文件中使用它们,如下所示:
using AdjusterSave.Helpers;
但是,在尝试使用这些方法时,我仍然会收到以下错误。当我这样称呼时:
GetDropdowns();
我收到此错误:
当前上下文中不存在名称“GetDropdowns”。
修改
尝试使用类似的方法(在〜/ Controllers / AdjusterController.cs中):
public ActionResult ViewProfile()
{
// a bunch of code like this:
User user = db.Users.Where(x => x.username == HttpContext.User.Identity.Name).FirstOrDefault();
AdjusterViewProfileInfo model = new AdjusterViewProfileInfo();
// get name
model.namePrefix = user.namePrefix;
model.firstName = user.firstName;
model.middleInitial = user.middleInitial;
model.lastName = user.lastName;
model.nameSuffix = user.nameSuffix;
// end then, finally,
GetDropdowns();
// followed by...
TempData["CurrentPage"] = "ViewProfile";
return View("", _layout, model);
}
修改
GetDropdowns示例:
public void GetDropdowns(this Controller controller)
{
// get name prefixes
List<SelectListItem> prefixList = new List<SelectListItem>();
prefixList.Add(new SelectListItem { Value = "Mr.", Text = "Mr." });
prefixList.Add(new SelectListItem { Value = "Mrs.", Text = "Mrs." });
prefixList.Add(new SelectListItem { Value = "Ms.", Text = "Ms." });
ViewBag.PrefixList = new SelectList(prefixList, "Value", "Text");
}
答案 0 :(得分:4)
你做错了。你需要做的是创建一个这样的静态类:
public static class Helpers
{
public static void GetDropdowns(this Controller controller)
{
// var username = controller.HttpContext.User.Identity.Name;
// get name prefixes
List<SelectListItem> prefixList = new List<SelectListItem>();
prefixList.Add(new SelectListItem { Value = "Mr.", Text = "Mr." });
prefixList.Add(new SelectListItem { Value = "Mrs.", Text = "Mrs." });
prefixList.Add(new SelectListItem { Value = "Ms.", Text = "Ms." });
controller.ViewBag.PrefixList = new SelectList(prefixList, "Value", "Text");
}
}
并且,您可以在控制器中使用它,如下所示:
this.GetDropdowns();
答案 1 :(得分:2)
您可以使用扩展方法代替Controller中的继承:
public static class Helpers
{
public static void GetDropdowns(this Controller controller)
{
// do something with the "controller", for sample:
controller.ViewBag = new List<string>();
}
}
您可以通过controller
参数在控制器上访问所需的一切。
在您的控制器中,您可以执行以下操作:
public ActionResult Index()
{
// just call it, and the .net framework will pass "this" controller to your extension methodo
GetDropdowns();
}
答案 2 :(得分:2)
如果您想调用GetDropdowns(),您可以:
实例化帮助并调用它:
new Helpers().GetDropdowns();
将方法GetDropdowns设为静态:
public static void GetDropdowns()
{
}
然后调用它:
Helpers.GetDropdowns();
您也可以从Helpers继承AdjusterController:
public class AdjusterController : Helpers
{
}
然后像你一样调用它。一切都取决于你感兴趣的东西。我猜你不应该从Controller继承Helpers并使方法保持静态,但这只是猜测。