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

查看:42
本文介绍了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 行代码,但随后我必须为每个字段都这样做,这太傻了,太丑了.相反,我想获取该字段(字符串值),将其传递给一个方法并返回另一个字符串值.然后对每个领域都这样做.

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.

所以,这是我的问题:

如何从视图调用方法?

我意识到我在这里可能问错了问题.答案可能是我没有,我应该使用本地模型并将我从外部 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:从视图调用控制器方法"(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天全站免登陆