1

リンクに複数のアクションを含めることができるかどうか疑問に思っていました。たとえば、次のような複数のリンクが必要な場合:

http://www.mywebsite.com/(コントローラー)/(ID)/(アクション)

[http://]www.mywebsite.com/user/Micheal/EditMovies [http://]www.mywebsite.com/user/Micheal/EditFavorites

これを行う何らかの方法はありますか?そうでない場合、関数で複数の ID を指定し、ケースを使用して送信先のページを決定する必要がありますか?

私の UserController.cs には次のものがあります。

public ActionResult Index(string username)
    {
        if (username != null)
        {
            try
            {
                var userid = (Membership.GetUser(username, false).ProviderUserKey);
                Users user = entity.User.Find(userid);
                return View(user);   
            }
            catch (Exception e)
            {

            }
        }
        return RedirectToAction("", "Home");
    }

私のルートには次のものがあります。

routes.MapRoute(
            name: "User",
            url: "User/{username}",
            defaults: new { controller = "User", action = "Index" }
        );

私がやろうとしているのは、次のようなことができるように、2番目のアクションに追加の機能を持たせることです:

User/{username}/{actionsAdditional}

そして、私のUserControllerでは、2番目のアクションactionAdditionalをリードするアクションをさらに配置できます

public ActionResult Index(string username)
    {
        if (username != null)
        {
            try
            {
                var userid = (Membership.GetUser(username, false).ProviderUserKey);
                Users user = entity.User.Find(userid);
                return View(user);   
            }
            catch (Exception e)
            {

            }
        }
        return RedirectToAction("", "Home");
    }

public ActionResult EditFavorites()
    {

//DoStuff }

4

1 に答える 1

0

これは複数の方法で実行できますが、ここではその 1 つだけを示します。

これを処理するルートを設定します。

routes.MapRoute("UserEditsThings",
    "user/{id}/edit/{thingToEdit}",
    new { controller = "UserController", action="Edit" },
    new { thingToEdit = ValidThingsToEditConstraint() }
);

次に、コントローラーでのアクションは次のUserようになります。

public ActionResult Edit(ThingToEdit thingToEdit) {
    ThingToEditViewModel viewModel = new ThingToEditViewModel(thingToEdit);
    return View(viewModel);
}

これRouteConstraintは、彼らの入力 (thingToEdit) を受け取り、それが有効であることを確認するものです (カスタム ModelBinder のように、いくつかの場所でこれを行うことができます)。

public class ValidThingsToEditConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        //simplistic implementation simply to show what's possible.
        return values['thingToEdit'] == "Favorites" || values['thingToEdit'] == "Movies";

    }
}

これで、ムービーとお気に入りの両方を編集するための 1 つのメソッドを持つことができ、パラメータを追加するだけで、編集中のものの「タイプ」を示すことができます。

現在のルートを維持したい場合は、次のことができるはずです。

routes.MapRoute("UserEditsThings",
    "user/{id}/edit{thingToEdit}",
    new { controller = "UserController", action="Edit" },
    new { thingToEdit = ValidThingsToEditConstraint() }
);

私は約 7 か月間 ASP.NET MVC から離れていたので、これは少し錆びている可能性があります。構文エラーについてはテストされておらず、Python のビットが透けて見える可能性があります。しかし、それはあなたをそこに連れて行くはずです。

于 2013-07-12T02:20:13.820 に答える