Last active
October 19, 2016 21:02
-
-
Save pmunin/4ae404acad958e3f3748bc76396877d9 to your computer and use it in GitHub Desktop.
ASP.NET MVC WebViewPageExtensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Web.Mvc; | |
| using System.Web.WebPages; | |
| using System.Linq; | |
| public static class WebViewPageExtensions | |
| { | |
| /// <summary> | |
| /// Functionality similar to the controller's TryUpdateModel() protected method | |
| /// </summary> | |
| public static bool TryUpdateModel<TModel>(this WebViewPage page, TModel model, string prefix = "") where TModel : class | |
| { | |
| if (model == null) | |
| { | |
| throw new ArgumentNullException("model"); | |
| } | |
| var pageModelState = page.ViewData.ModelState; | |
| var bindingContext = new ModelBindingContext | |
| { | |
| ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)), | |
| ModelName = prefix, | |
| ModelState = pageModelState, | |
| //PropertyFilter = propertyFilter, | |
| ValueProvider = page.ViewContext.Controller.ValueProvider | |
| }; | |
| var binder = ModelBinders.Binders.GetBinder(typeof(TModel)); | |
| binder.BindModel(page.ViewContext.Controller.ControllerContext, bindingContext); | |
| return pageModelState.IsValid; | |
| } | |
| /// <summary> | |
| /// Uses TemplateStack.Stack to return parents | |
| /// </summary> | |
| /// <param name="page"></param> | |
| /// <returns></returns> | |
| public static IEnumerable<WebPageRenderingBase> GetPageStack(this WebPageRenderingBase page) | |
| { | |
| var method = typeof(TemplateStack).GetMethod("GetStack", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); | |
| var res = method.Invoke(null, new object[] { page.Context }) as Stack<ITemplateFile>; | |
| return res.OfType<WebPageRenderingBase>(); | |
| } | |
| /// <summary> | |
| /// Uses TemplateStack.Stack to return parent | |
| /// </summary> | |
| /// <param name="page"></param> | |
| /// <returns></returns> | |
| public static WebPageRenderingBase GetPageParent(this WebPageRenderingBase page) | |
| { | |
| return GetPageStack(page).Skip(1).FirstOrDefault(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment