2017年7月26日 星期三

[ASP.NET] MVC - Default action for no-matched actions in controller

 ASP.NET    MVC    action  


Introduction


Here is an example of catching non-matched Action in Controller, and then redirect to another Action (which is already implemented).



Environment


MVC 5.2.3



Implement


MVC : Controller

public class TestController : Controller
{
        public ActionResult Index(string actionName)
        {
            var viewModel = this.getViewModel(actionName);

            if(viewModel!=null)
                return View(viewModel);
            else
                throw new HttpException(404, "Page Not Found");
        }


        /// <summary>
        /// Not matche actions will come here
        /// </summary>
        /// <param name="actionName"></param>
        protected override void HandleUnknownAction(string actionName)
        {
            RedirectToAction("Index", new { actionName = actionName }).ExecuteResult(this.ControllerContext);
        }
}



Result

When I browse the following uri:
/Test/NonImplementedAction

We will be redirected to
/Test?actionName= NonImplementedAction

Which equals to /Test/Index?actionName= NonImplementedAction




Reference



沒有留言:

張貼留言