【问题标题】:Is there a builtin way of filling up values in the Model from cookies?是否有一种内置方法可以从 cookie 中填充模型中的值?
【发布时间】:2011-02-15 01:23:39
【问题描述】:

假设我目前有一个Controller 和以下Action

    public ActionResult Index() {

        return View();
    }

我想知道如果不是这个,我可以有类似的东西

    public ActionResult Index(MyModel model) {

        return View();
    }

模型在某种程度上已经被存储在 cookie 中的数据填满了。

【问题讨论】:

    标签: c# .net asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    您可以编写一个自定义模型绑定器,该绑定器将从 cookie 中填充视图模型:

    public class MyModelCookiesModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var cookie = controllerContext.HttpContext.Request.Cookies["someCookie"];
            MyModel myModel = GetModelFromCookie(cookie);
            return myModel;
        }
    
        private MyModel GetModelFromCookie(HttpCookie cookie)
        {
            // TODO:
            throw new NotImplementedException();
        }
    }
    

    然后在Application_Start注册:

    ModelBinders.Binders.Add(typeof(MyModel), new MyModelCookiesModelBinder());
    

    最后你可以:

    public ActionResult Index(MyModel model) 
    {
        return View();
    }
    

    将从 cookie 中填充模型的位置。

    【讨论】:

    • 这看起来很有趣,但这基本上必须为我自己做。我一直在寻找的东西类似于您使用 HttpPost 获得的东西,它“免费”为您填充它。
    【解决方案2】:

    不。它必须是一个 [HttpPost] 操作。

    [HttpPost]
    public ActionResult Index(MyModel model)
    {
     ...
     ...
     ...
    }
    

    据我所知[HttpGet]是不指定属性的默认值,只能取简单的值类型。

    public ActionResult Index(int id)
    {
         MyModel model = dataLayer.getModel(id);
         return View(model);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-16
      • 2010-09-13
      • 2018-04-08
      • 2017-05-07
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      相关资源
      最近更新 更多