Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

c# - Calling controller action method directly from Razor View

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

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

There has to be an easy way to call a method from the razor view engine.

It is within a foreach loop.

I need GetUserName(item.userID)

The below code is in my controller:

[ChildActionOnly]
public string GetUserName(int userID)
{
     ProPit_User user = db.ProPit_User.Find(userID);

     return user.username;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...