行动名称的目的

使用“ ActionName”属性为操作方法设置别名有什么好处?我实在看不出它有什么好处,因为它为用户提供了使用其他名称调用 action 方法的选项。在指定别名之后,用户只能使用别名调用操作方法。但是,如果这是必需的,那么为什么用户不更改操作方法的名称,而是为它指定别名呢?

如果有人能为我提供一个使用“ ActionName”的例子,我将非常感激。在这个场景中,它可以提供很大的好处,或者最好使用它。

72793 次浏览

It allows you to start your action with a number or include any character that .net does not allow in an identifier. - The most common reason is it allows you have two Actions with the same signature (see the GET/POST Delete actions of any scaffolded controller)

For example: you could allow dashes within your url action name http://example.com/products/create-product vs http://example.com/products/createproduct or http://example.com/products/create_product.

public class ProductsController {


[ActionName("create-product")]
public ActionResult CreateProduct() {
return View();
}


}

It is also useful if you have two Actions with the same signature that should have the same url.

A simple example:

public ActionResult SomeAction()
{
...
}


[ActionName("SomeAction")]
[HttpPost]
public ActionResult SomeActionPost()
{
...
}

I use it when the user downloads a report so that they can open their csv file directly into Excel easily.

[ActionName("GetCSV.csv")]
public ActionResult GetCSV(){
string csv = CreateCSV();
return new ContentResult() { Content = csv, ContentEncoding = System.Text.Encoding.UTF8, ContentType = "text/csv" };
}

It is also helpful when you need to implement method overloading.

 public ActionResult ActorView()
{


return View(actorsList);
}




[ActionName("ActorViewOverload")]
public ActionResult ActorView(int id)
{
return RedirectToAction("ActorView","Home");
}
`

Here one ActorView accepts no parameters and the other accepts int. The first method used for viewing actor list and the other one is used for showing the same actor list after deleting an item with ID as 'id'. You can use action name as 'ActorViewOverload' whereever you need method overloading.

Try this code:

public class ProductsController
{


[ActionName("create-product")]
public ActionResult CreateProduct()
{
return View("CreateProduct");
}


}

This class represents an attribute that is used for the name of an action. It also allows developers to use a different action name than the method name.