ActionResult选择器和设计模式

德米特里·博伊科

我想ActionResult根据用户的选择创建类似的结构

我的问题是,它是否可以以更通用的方式完成,或者至少以某种方式即兴完成?

我只是要确保它做得很好。

这是我的代码。

<p>A Partial Control that is initialized on Server-Side</p>
@{
    <h2>@ViewBag.InitializeUserControl</h2>
    Html.RenderAction("ShowGadget",new { actionName = (string)@ViewBag.InitializeUserControl } );      
}

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            @ViewBag.InitializeUserControl = "InitializeUserControl2"; // IT GOES FROM A DATABASE
            return View(new HomeModel());
        }

        public ActionResult ShowGadget(string actionName)
        {
            var gadgetPresenter = new GadgetPresenter();
            return gadgetPresenter.GetActionResult(actionName);
        }
    }


    public class GadgetPresenter : Controller
    {
        public ActionResult GetActionResult(string actionName)
        {
            if (string.IsNullOrEmpty(actionName))
            {
                return DefaultUserControl();
            }
            else
            {
                if (actionName.Equals("InitializeUserControl"))
                {
                    return InitializeUserControl();
                }
                else if (actionName.Equals("InitializeUserControl2"))
                {
                    return InitializeUserControl2();
                }
                else
                    return DefaultUserControl();
            }
        }

        public ActionResult InitializeUserControl2()
        {
            ColorModel colorModel = new ColorModel
            {
                Width = 100,
                Height = 100,
                RGBColor = "#FF0000"
            };

            return PartialView("UserControls/ColorBlockUserControl2", colorModel);
        }

        public ActionResult InitializeUserControl()
        {
            ColorModel colorModel = new ColorModel
            {
                Width = 200,
                Height = 200,
                RGBColor = "#FF0000"
            };

            return PartialView("UserControls/ColorBlockUserControl", colorModel);
        }

        public ActionResult DefaultUserControl()
        {
            return PartialView("UserControls/DummyControl");
        }

    }
Moby的特技双人

我想我知道您要执行的操作,但是我认为您可能会强制输入错误的模式。因此,由于这将是数据库中的值,因此需要确保以下几点:

  1. 如果相关项目存在或不存在,则您的应用会正常失败。
  2. 您正在使用约定而非配置来辅助可维护性。

我认为您需要的模式/技术是移动视图引擎。以Scott Hanselman的MVC3移动视图引擎示例)为例。请注意,引擎如何查找.mobile.cshtml视图,如果不存在,将退回到普通的.cshtml视图。显然,它现在已内置在MVC4中,但是该技术对于多种用途都是可行的。

您可以根据自己的需要对此进行调整,查找与客户有关的存储数据库值的会话变量或类似变量(Singleton over Session将是我的方法),以获取视图前缀并为其提供不同的前缀。

回退是优美的,并且模式全都与约定和注入有关。当然,这是我要解决您的问题的方法。我希望这对您有所帮助,无论您是否最终使用该技术。祝你好运,Godspeed!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章