将表单发布到不在MVC中的不同控制器操作

时间:2017-08-10 12:40:13

标签: c# forms asp.net-mvc-4 asp.net-mvc-routing

我已在 RouteConfig.cs 中定义了默认路线,如下所示:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{action}/{id}",
                defaults: new { controller = "BackEnd", action = "Index", id = UrlParameter.Optional }
            );
        }

BackEnd控制器:

public class BackEndController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

帐户控制器:

public class AccountController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken()]
        public ActionResult LoginForm(Login item)
        {
            //Some code goes here...
            return RedirectToAction("Index");
        }
    }

登录部分:

    using (Html.BeginForm("LoginForm", "Account", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        @Html.LabelFor(m => m.Username)
        @Html.TextBoxFor(m => m.Username, new { placeholder = "Username" })
        @Html.ValidationMessageFor(m => m.Username)

        @Html.LabelFor(m => m.Password)
        @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
        @Html.ValidationMessageFor(m => m.Password)

        <input type="submit" value="Login" />
    }

我的表单未提交给控制器操作Account/Login

1 个答案:

答案 0 :(得分:0)

然后你将不得不添加另一个路由来处理该url。然而,这违背了基于约定的路由的目的。

routes.MapRoute(
    name: "Login",
    url: "Login",
    defaults: new { controller = "Account", action = "LoginForm" }
);

routes.MapRoute(
    name: "Default",
    url: "{action}/{id}",
    defaults: new { controller = "BackEnd", action = "Index", id = UrlParameter.Optional }
);