ASP.Net MVC:从调用视图的方法 [英] ASP.Net MVC: Calling a method from a view

查看:124
本文介绍了ASP.Net MVC:从调用视图的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用程序控制器获取来自外部API数据(模型)(所以没有使用模型类),并传递到视图。数据(模型)具有在其中有几个字段(串值)多个对象的容器。每个对象,一个视图进行迭代,并调用另一个视图中绘制它们。这在域视图迭代(字符串值),并提请他们。

In my MVC app the controller gets the data (model) from an external API (so there is no model class being used) and passes that to the view. The data (model) has a container in which there are several objects with several fields (string values). One view iterates over each object and calls another view to draw each of them. This view iterates over the fields (string values) and draws them.

在此处,它为我变得棘手。有时候我想做的字段(字符串值)一些特殊格式。我可以写20行code的格式,但后来我不得不这样做的每一个领域,这将仅仅是愚蠢的,哦,这么难看。相反,我想借场(字符串值),它传递给方法,并得到另一个字符串值回。然后执行,对于每一个领域。

Here's where it gets tricky for me. Sometimes I want to do some special formatting on the fields (string values). I could write 20 lines of code for the formatting but then I would have to do that for each and every field and that would just be silly and oh so ugly. Instead I would like to take the field (string value), pass it to a method and get another string value back. And then do that for every field.

所以,这里是我的问题:

So, here's my question:

如何调用从视图的方法?

我意识到我可能在这里问错了问题。答案很可能是,我不这样做,我应该使用本地模型和反序列化,我从外部API得到我的地方的模型,然后在我的局部模型对象,做了特殊格式之前,我通过它的观点。但我希望有一些方法可以让我从视图中调用一个方法来代替。主要是因为它似乎是一个很大的开销,以自定义对象我从API,它轮流包含了很多其他的自定义对象,为我建立当地的自定义对象转换得到的。而且,我不知道这样做的最好办法是什么。

I realize that I may be asking the wrong question here. The answer is probably that I don't, and that I should use a local model and deserialize the object that I get from the external API to my local model and then, in my local model, do the "special formatting" before I pass it to the view. But I'm hoping there is some way I can call a method from a view instead. Mostly because it seems like a lot of overhead to convert the custom object I get from the API, which in turns contains a lot of other custom objects, into local custom objects that I build. And also, I'm not sure what the best way of doing that would be.

免责声明:我知道类似线程ASP.NET MVC:从调用视图控制器法(<一href=\"http://stackoverflow.com/questions/2473025/asp-net-mvc-calling-a-controller-method-from-view\">ASP.NET MVC:从调用视图控制器的方法),但我没有看到如何回答我的问题。

Disclaimer: I'm aware of the similar thread "ASP.NET MVC: calling a controller method from view" (ASP.NET MVC: calling a controller method from view) but I don't see how that answers my question.

推荐答案

这是你如何调用控制器上的实例方法:

This is how you call an instance method on the Controller:

@{
  ((HomeController)this.ViewContext.Controller).Method1();
}

这是你如何调用静态方法,任何类

This is how you call a static method in any class

@{
    SomeClass.Method();
}

这将工作假设方法是公共的和看得见的视图。

This will work assuming the method is public and visible to the view.

这篇关于ASP.Net MVC:从调用视图的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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