错误已使用相同的参数类型定义了一个名为“索引"的成员 [英] Error already defines a member called 'Index' with the same parameter types

查看:72
本文介绍了错误已使用相同的参数类型定义了一个名为“索引"的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我有以下两种方法;

In my Controller i have the following 2 methods;

[ActionName("index")]
public ActionResult Index()
{
    return View();
}

and

 public ActionResult Index()
 {
    var m =MyMod();

    return View(m);

 }

即使我使用了 [ActionName("index")] ,我仍然收到一条错误消息,指出 Error 1类型'MyProject.Controllers.MyController'已经定义了一个名为'Index'的成员,相同的参数类型

Even though i used [ActionName("index")] i get an error saying that Error 1 Type 'MyProject.Controllers.MyController' already defines a member called 'Index' with the same parameter types

我该如何预防?

推荐答案

否,这是不可能的,您不能在同一控制器上使用相同的HTTP动词进行两个具有相同名称的操作.同样从C#的角度来看,同一类上不能有两个具有相同名称和参数的方法.编译器不允许您这样做.

No, this is not possible, you cannot have 2 actions with the same name on the same controller using the same HTTP verb. Also from C#'s perspective you cannot have 2 methods on the same class with the same name and same parameters. The compiler won't let you do that.

您可以使用不同的HTTP动词使这两个动作之一可用.当您有两个具有相同名称的操作时,通常这是惯例.第一个用于呈现视图,第二个用于装饰 [HttpPost] 属性,并用于处理从视图提交的表单.post操作还采用视图模型作为包含表单提交字段的参数.因此,这两种方法具有不同的签名,这将使编译器感到满意.这是推荐的方法:

You could make one of the 2 actions be accessible with a different HTTP verb. This is usually the convention when you have 2 actions with the same name. The first is used to render a view and the second is decorated with the [HttpPost] attribute and used to process the form submit from the view. The post action also takes a view model as parameter containing the form submission fields. So the 2 methods have different signatures and it will make the compiler happy. Here's the recommended approach:

public ActionResult Index()
{     
    MyViewModel model = ...
    return View(model);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    ...
} 

这篇关于错误已使用相同的参数类型定义了一个名为“索引"的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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