Calling controller action method directly from Razor View

前端 未结 2 1303
误落风尘
误落风尘 2020-12-30 06:30

I looked around and couldn\'t find an easy solution.

I\'ve tried @GetUserName which doesn\'t work.
I\'ve tried @ { GetUserName which do

2条回答
  •  盖世英雄少女心
    2020-12-30 07:13

    Trying to call a controller action method directly from your view is usually a sign of bad design.

    You have a few options, depending on what you are trying to do:

    1. Avoid calling the method, instead put the data in your model, and render the model
    2. Use Html.RenderAction
    3. Put the method in another class and use normal function syntax.

    (1) is usually my default approach, often incorporating DisplayTemplates and EditorTemplates

    For (3), e.g.

    public static class Util
    {
        public string MyUtilMethod(int blah)
    }
    

    And the view:

    @Util.MyUtilMethod(1)
    

提交回复
热议问题