1

~/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");

}
4

3 に答える 3

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();
于 2013-07-15T14:31:52.867 に答える
2

コントローラーから継承する代わりに、拡張メソッドを使用できます。

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();
}
于 2013-07-15T14:30:31.863 に答える