操作名称选择器使用

/***********************************操作名称选择器*******************************************/

using System.Web.Mvc;
using Chapter15.Areas.ActionNameSelector.Utility;

namespace Chapter15.Areas.ActionNameSelector.Controllers
{
    public class ActionNameController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [Product]
        public ActionResult Product(int productId)
        {
            return Content("You asked for product #" + productId);
        }
    }
}

/****************************ProductAttribute.cs****************************************/

using System;
using System.Reflection;
using System.Web.Mvc;

namespace Chapter15.Areas.ActionNameSelector.Utility
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class ProductAttribute : ActionNameSelectorAttribute
    {
        private const string PREFIX = "product-";

        public override bool IsValidName(ControllerContext controllerContext,
                                         string actionName,
                                         MethodInfo methodInfo)
        {
            if (!actionName.StartsWith(PREFIX, StringComparison.InvariantCultureIgnoreCase))
                return false;

            controllerContext.RequestContext.RouteData.Values.Add("productId", actionName.Substring(PREFIX.Length));
            return true;
        }
    }
}

/*****************************Index.cshtml**********************************************/

@{ ViewBag.Title = "Action Name Selector Sample"; }

<ul>
@for (int i = 1; i < 20; i++) {
    <li><a href="/ActionName/product-@i">Product #@i</a></li>
}
</ul>
 

发布了488 篇原创文章 · 获赞 73 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/dxm809/article/details/104495067
今日推荐