Let's say I curre开发者_运维问答ntly have a Controller
with the following Action
:
public ActionResult Index() {
return View();
}
I'd like to know if instead of this, I could have something like
public ActionResult Index(MyModel model) {
return View();
}
where the model is in some way already filled up with data stored in the cookies.
You could write a custom model binder which will fill the view model from cookies:
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();
}
}
then register it in Application_Start
:
ModelBinders.Binders.Add(typeof(MyModel), new MyModelCookiesModelBinder());
and finally you could have:
public ActionResult Index(MyModel model)
{
return View();
}
where the model will be populated from the cookie.
Nope. It would have to be a [HttpPost] action.
[HttpPost]
public ActionResult Index(MyModel model)
{
...
...
...
}
As far as I know, [HttpGet]
, which is the default if you don't specify an attribute, can only take simple value types.
public ActionResult Index(int id)
{
MyModel model = dataLayer.getModel(id);
return View(model);
}
精彩评论