1

私は 2 つのアクション メソッドを持つ ProdcutsController を持っています。索引と詳細。Index は製品のリストを返し、Details は選択した製品 ID の詳細を返します。

だから私のURLは似ています

sitename/Products/   

インデックス ビューを読み込み、製品のリストを表示します。

 sitename/Products/Details/1234  

詳細ビューをロードして、製品 1234 の詳細を表示します。

ここで、2 番目の URL から「詳細」という単語を避けたいと思います。次のように見えるように

   sitename/Products/1234 

アクションメソッドの名前を「詳細」から「インデックス」にパラメータを付けて変更しようとしました。しかし、エラー " Method is is ambiguous"が表示されました

私はこれを試しました

 public ActionResult Index()
{
    //code to load Listing view
}
public ActionResult Index(string? id)
{
    //code to load details view
}

私は今、このエラーが発生しています

The type 'string' must be a non-nullable value type in order to use
it as parameter 'T' in the generic type or method 'System.Nullable<T>

メソッドのオーバーロードをサポートしていないことに気付きました! どうすればこれを処理できますか? ルート定義を更新する必要がありますか?

4

3 に答える 3

1

これを使って:

public ActionResult Index(int? id)
{
    //code to load details view
}

値が整数型であると仮定します。

これは別のオプションです。

public ActionResult Index(string id)
{
    //code to load details view
}

Astringは参照型であるため、nullを必要とせずに をすでに割り当てることができますNullable<T>

于 2011-12-25T19:09:10.397 に答える
0

2つのルートを作成し、ルート制約を使用できます。

Global.asax

        routes.MapRoute(
            "Details", // Route name
            "{controller}/{id}", // URL with parameters
            new { controller = "Products", action = "Details" }, // Parameter defaults
            new { id = @"\d+" }
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

最初のルートには、idに1桁以上の数字が必要な制約があります。~/home/aboutこの制約のため、などのルートはキャッチされません。

ProductsController

    public ActionResult Index()
    {
        // ...
    }

    public ActionResult Details(int id)
    {
        // ...
    }
于 2011-12-25T21:15:03.430 に答える
0

Action メソッドを 1 つだけ使用できます。

何かのようなもの:

public ActionResult Index(int? Id)
{
  if(Id.HasValue)
  {
    //Show Details View
  }
  else
  {
    //Show List View
  }
}
于 2011-12-25T19:12:40.557 に答える