C# ASP.Net MVC:从视图调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15398177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:39:38  来源:igfitidea点击:

ASP.Net MVC: Calling a method from a view

c#asp.net-mvcasp.net-mvc-4

提问by doosh

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.

在我的 MVC 应用程序中,控制器从外部 API 获取数据(模型)(因此没有使用模型类)并将其传递给视图。数据(模型)有一个容器,其中有多个具有多个字段(字符串值)的对象。一个视图遍历每个对象并调用另一个视图来绘制每个对象。此视图遍历字段(字符串值)并绘制它们。

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.

这就是我觉得棘手的地方。有时我想对字段(字符串值)做一些特殊的格式化。我可以为格式化编写 20 行代码,但随后我必须为每个字段都这样做,这太愚蠢了,太丑了。相反,我想获取该字段(字符串值),将其传递给一个方法并返回另一个字符串值。然后对每个领域都这样做。

So, here's my question:

所以,这是我的问题:

How do I call a method from a view?

如何从视图调用方法?

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.

我意识到我在这里可能问错了问题。答案可能是我没有,我应该使用本地模型并将我从外部 API 获取的对象反序列化到本地模型,然后在本地模型中,在通过之前执行“特殊格式设置”它的观点。但我希望有某种方式可以从视图中调用方法。主要是因为将我从 API 获得的自定义对象(又包含许多其他自定义对象)转换为我构建的本地自定义对象似乎需要大量开销。而且,我不确定这样做的最佳方式是什么。

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.

免责声明:我知道类似的线程“ASP.NET MVC:从视图调用控制器方法”(ASP.NET MVC:从视图调用控制器方法),但我不知道它如何回答我的问题。

采纳答案by lahsrah

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.

假设该方法是公共的并且对视图可见,这将起作用。

回答by Amine Chafai

You can implement a static formatting method or an HTML helper, then use this syntaxe :

您可以实现静态格式化方法或 HTML 帮助程序,然后使用以下语法:

@using class_of_method_namespace
...
// HTML page here
@className.MethodName()

or in case of HTML Helper

或者在 HTML Helper 的情况下

@Html.MehtodName()

回答by tkestowicz

You should create custom helper for just changing string format except using controller call.

除了使用控制器调用之外,您应该创建自定义帮助程序来更改字符串格式。

回答by viperguynaz

Building on Amine's answer, create a helper like:

以 Amine 的回答为基础,创建一个助手,如:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString CurrencyFormat(this HtmlHelper helper, string value)
    {
        var result = string.Format("{0:C2}", value);
        return new MvcHtmlString(result);
    }
}

in your view: use @Html.CurrencyFormat(model.value)

在您看来:使用 @Html.CurrencyFormat(model.value)

If you are doing simple formating like Standard Numeric Formats, then simple use string.Format()in your view like in the helper example above:

如果你正在做像Standard Numeric Formats这样的简单格式化,那么在你的视图中简单地使用string.Format()就像上面的帮助示例一样:

@string.Format("{0:C2}", model.value)

回答by Illidan

Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.

不应从视图中调用控制器。这就是 MVC 的全部思想——明确的关注点分离。

If you need to call controller from View - you are doing something wrong. Time for refactoring.

如果您需要从 View 调用控制器 - 您做错了什么。是时候重构了。

回答by Basheer AL-MOMANI

why You don't use Ajaxto

你为什么不使用Ajax

its simple and does not require page refreshand has success and errorcallbacks

它很简单,不需要page refresh并且有success and error回调

take look at my samlpe

看看我的样品

<a id="ResendVerificationCode" >@Resource_en.ResendVerificationCode</a>

and in JQuery

在 JQuery 中

 $("#ResendVerificationCode").on("click", function() {
                getUserbyPhoneIfNotRegisterd($("#phone").val());
 });

and this is my ajax which call my controller and my controller and return object from database

这是我的ajax,它调用我的控制器和我的控制器并从数据库返回对象

function getUserbyPhoneIfNotRegisterd(userphone) {

              $.ajax({
                    type: "GET",
                    dataType: "Json",
                    url: '@Url.Action("GetUserByPhone", "User")' + '?phone=' + userphone,
                    async: false,
                    success: function(data) {
                        if (data == null || data.data == null) {
                            ErrorMessage("", "@Resource_en.YourPhoneDoesNotExistInOurDatabase");
                        } else {
                            user = data[Object.keys(data)[0]];
                                AddVereCode(user.ID);// anather Ajax call 
                                SuccessMessage("Done", "@Resource_en.VerificationCodeSentSuccessfully", "Done");
                        }
                    },
                    error: function() {
                        ErrorMessage("", '@Resource_en.ErrorOccourd');
                    }
                });
            }

回答by bthn

I tried lashrah's answer and it worked after changing syntax a little bit. this is what worked for me:

我尝试了 lashrah 的答案,并在稍微更改语法后起作用。这对我有用:

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

回答by live-love

You should not call a controller from the view.

您不应该从视图中调用控制器。

Add a property to your view model, set it in the controller, and use it in the view.

向您的视图模型添加一个属性,在控制器中设置它,然后在视图中使用它。

Here is an example:

下面是一个例子:

MyViewModel.cs:

MyViewModel.cs:

public class MyViewModel
{   ...
    public bool ShowAdmin { get; set; }
}

MyController.cs:

我的控制器.cs:

public ViewResult GetAdminMenu()
    {
        MyViewModelmodel = new MyViewModel();            

        model.ShowAdmin = userHasPermission("Admin"); 

        return View(model);
    }

MyView.cshtml:

MyView.cshtml:

@model MyProj.ViewModels.MyViewModel


@if (@Model.ShowAdmin)
{
   <!-- admin links here-->
}

..\Views\Shared\ _Layout.cshtml:

..\Views\Shared\_Layout.cshtml:

    @using MyProj.ViewModels.Common;
....
    <div>    
        @Html.Action("GetAdminMenu", "Layout")
    </div>