MRCollective / ChameleonForms

Shape-shifting your forms experience in ASP.NET Core MVC
MIT License
254 stars 56 forks source link

Allow Html to be changed to a different model type #95

Closed robdmoore closed 8 years ago

robdmoore commented 10 years ago

e.g. something like this, maybe add a BeginChameleonForm overload that takes the model type as a shorthand too...

    public static class HtmlHelperExtensions
    {
        public static HtmlHelper<TNewModel> ForModel<TNewModel>(this HtmlHelper html, TNewModel modelInstance = default(TNewModel))
        {
            var tempDataDictionary = new ViewDataDictionary(html.ViewContext.ViewData) {Model = modelInstance};
            var newViewDataDictionary = new ViewDataDictionary<TNewModel>(tempDataDictionary);
            var newViewContext = new ViewContext(
                html.ViewContext.Controller.ControllerContext,
                html.ViewContext.View,
                newViewDataDictionary,
                html.ViewContext.TempData,
                html.ViewContext.Writer
            );
            var newViewData = new ViewPage<TNewModel>
            {
                ViewContext = newViewContext,
                ViewData = newViewDataDictionary
            };
            newViewData.InitHelpers();
            return new HtmlHelper<TNewModel>(newViewContext, newViewData);
        }
    }