调用控制器中的方法 [英] Calling a method in the controller

查看:184
本文介绍了调用控制器中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个关于ASP.NET MVC 3的新手,但我有一个简单的问题。 是否有可能调用从CSHTML(剃刀)第一个控制器的方法?

I'm a newbie about ASP.NET MVC 3, but I have a simple question. Is it possible to call a Controller method from an CSHTML (Razor) page?

例如:

xxxControl.cs:

xxxControl.cs:

public String Bla(TestModel pModel)
{
    return ...
}

index.cshtml:

index.cshtml:

@Bla(Model) <-- Error

感谢。

更新:

感谢@Nathan。这不是一个好主意,这样做在这条路上。 我们的目标是:我需要一些格式化字符串型的字段。但是,在我把code,它返回一个格式化字符串的情况下?

Thanks @Nathan. This isn't a good idea to do this on this way. The goal is: I need some formatting string for a field of the Model. But where I put the code that return a formatting String in the case?

推荐答案

它被认为是不好的做法,以便调用位于控制器上的方法。通常它是一个控制器的动作而填充一个模型,通过这个模型视图。如果你需要一些格式上的这种模式,您可以编写一个HTML帮手。

It is considered bad practice for a view to call methods located on a controller. Usually it is a controller action which populates a model and passes this model to the view. If you needed some formatting on this model you could write an HTML helper.

public static class HtmlExtensions
{
    public static IHtmlString Bla(this HtmlHelper<TestModel> htmlHelper)
    {
        TestModel model = htmlHelper.ViewData.Model;
        var value = string.Format("bla bla {0}", model.SomeProperty);
        return MvcHtmlString.Create(value);
    }
}

和你的观点:

@Html.Bla()

这篇关于调用控制器中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆