Example #1
1
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            // If custom errors are disabled, we need to let the normal ASP.NET exception handler
            // execute so that the user can see useful debugging information.
            if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            {
                return;
            }

            Exception exception = filterContext.Exception;

            // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
            // ignore it.
            if (new HttpException(null, exception).GetHttpCode() != 500)
            {
                return;
            }

            if (!ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }

            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);

            if (this._logger.IsErrorEnabled)
            {
                this._logger.Error(string.Format("An unexpected error occured while executing {0} in {1}.", actionName, controllerName), exception);
            }

            MessageViewData messageViewData = new MessageViewData();

            while (exception != null)
            {
                messageViewData.AddErrorMessage(this._localizer.GetString(exception.Message));
                exception = exception.InnerException;
            }
            var viewData = new ViewDataDictionary<HandleErrorInfo>(model);
            viewData["Messages"] = messageViewData;

            // Render error view
            filterContext.Result = new ViewResult
                                   	{
                                   		ViewName = View,
                                   		MasterName = Master,
                                   		ViewData = viewData,
                                   		TempData = filterContext.Controller.TempData
                                   	};

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
        }
Example #2
1
 public ColorPicker(ViewContext viewContext, IJavaScriptInitializer initializer, ViewDataDictionary viewData)
     : base(viewContext, initializer, viewData)
 {
     Palette = ColorPickerPalette.None;
     Enabled = true;
     Buttons = true;
 }
		public void Setup()
		{
			// WikiController setup (use WikiController as it's the one typically used by views)
			_container = new MocksAndStubsContainer();

			_applicationSettings = _container.ApplicationSettings;
			_context = _container.UserContext;
			_pageRepository = _container.PageRepository;
			_pluginFactory = _container.PluginFactory;
			_settingsService = _container.SettingsService;
			_userService = _container.UserService;
			_historyService = _container.HistoryService;
			_pageService = _container.PageService;

			_wikiController = new WikiController(_applicationSettings, _userService, _pageService, _context, _settingsService);
			_wikiController.SetFakeControllerContext("~/wiki/index/1");

			// HtmlHelper setup
			var viewDataDictionary = new ViewDataDictionary();
			_viewContext = new ViewContext(_wikiController.ControllerContext, new Mock<IView>().Object, viewDataDictionary, new TempDataDictionary(), new StringWriter());
			var mockViewDataContainer = new Mock<IViewDataContainer>();
			mockViewDataContainer.Setup(v => v.ViewData).Returns(viewDataDictionary);

			_htmlHelper = new HtmlHelper(_viewContext, mockViewDataContainer.Object);
		}
        public void EvalEvaluatesDictionaryThenModel() {
            var obj = new { Foo = "NotBar" };
            ViewDataDictionary vdd = new ViewDataDictionary(obj);
            vdd.Add("Foo", "Bar");

            Assert.AreEqual("Bar", vdd.Eval("Foo"));
        }
        public void RenderPartialWithViewNameAndViewData() {
            // Arrange
            SpyHtmlHelper helper = SpyHtmlHelper.Create();
            ViewDataDictionary viewData = new ViewDataDictionary();
            Mock<IViewEngine> engine = new Mock<IViewEngine>(MockBehavior.Strict);
            Mock<IView> view = new Mock<IView>(MockBehavior.Strict);

            helper.SpiedEngine = engine.Object;
            helper.ViewData["Foo"] = "Foo";
            viewData["Bar"] = "Bar";

            engine
                .Expect(e => e.FindPartialView(It.IsAny<ControllerContext>(), _partialViewName, It.IsAny<bool>()))
                .Returns(new ViewEngineResult(view.Object, engine.Object))
                .Verifiable();
            view
                .Expect(v => v.Render(It.IsAny<ViewContext>(), helper.ViewContext.HttpContext.Response.Output))
                .Callback<ViewContext, TextWriter>(
                    (viewContext, writer) => {
                        Assert.AreSame(helper.ViewContext.View, viewContext.View);
                        Assert.AreNotSame(helper.ViewData, viewContext.ViewData);
                        Assert.AreSame(helper.ViewContext.TempData, viewContext.TempData);
                        Assert.AreEqual("Bar", viewContext.ViewData["Bar"]);
                        Assert.IsFalse(viewContext.ViewData.ContainsKey("Foo"));
                    })
                .Verifiable();

            // Act
            helper.RenderPartial(_partialViewName, viewData);

            // Assert
            engine.Verify();
            view.Verify();
        }
        public void ViewBagAndViewDataStayInSync()
        {
            // Arrange
            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();
            ViewDataDictionary viewDataDictionary = new ViewDataDictionary() { { "A", 1 } };
            viewDataContainer.Setup(container => container.ViewData).Returns(viewDataDictionary);

            // Act
            AjaxHelper<object> ajaxHelper = new AjaxHelper<object>(new Mock<ViewContext>().Object, viewDataContainer.Object);
            ajaxHelper.ViewData["B"] = 2;
            ajaxHelper.ViewBag.C = 3;

            // Assert

            // Original ViewData should not be modified by redfined ViewData and ViewBag
            AjaxHelper nonGenericAjaxHelper = ajaxHelper;
            Assert.Single(nonGenericAjaxHelper.ViewData.Keys);
            Assert.Equal(1, nonGenericAjaxHelper.ViewData["A"]);
            Assert.Equal(1, nonGenericAjaxHelper.ViewBag.A);

            // Redefined ViewData and ViewBag should be in sync
            Assert.Equal(3, ajaxHelper.ViewData.Keys.Count);

            Assert.Equal(1, ajaxHelper.ViewData["A"]);
            Assert.Equal(2, ajaxHelper.ViewData["B"]);
            Assert.Equal(3, ajaxHelper.ViewData["C"]);

            Assert.Equal(1, ajaxHelper.ViewBag.A);
            Assert.Equal(2, ajaxHelper.ViewBag.B);
            Assert.Equal(3, ajaxHelper.ViewBag.C);
        }
Example #7
0
		/// <summary>
		/// Flushes the view data pool.
		/// </summary>
		/// <returns></returns>
		public String FlushViewDataPool( ViewDataDictionary viewData ) {
			if ( WebConfigSettings.GetWebConfigAppSetting( "isFlushDataPool" ) != "true" )
				return "<!-- ViewData isn't configed by appsettings.config. -->";

			var sb = new StringBuilder();

			if ( viewData.Count == 0 ) {
				sb.Append( "<!-- ViewData flushly is configed by appsettings.config but viewData is empty. -->" );

				return sb.ToString();
			}

			sb.Append( "<script language=\"javascript\" type=\"text/javascript\">\r\n" );

			foreach ( var keyValuePair in viewData ) {
				sb.Append( "\t\tvar dataPool_" + keyValuePair.Key + " = " );
				sb.Append( JavaScriptConvert.SerializeObject( keyValuePair.Value ) + ";\r\n" );
			}

			sb.Remove( sb.Length - 2 , 2 );

			sb.Append( "\r\n\t</script>" );

			return sb.ToString();
		}
 public void SetBrandSearchViewData(ProductSearchQuery query, ViewDataDictionary viewData)
 {
     ProductOptionSearchData productOptionSearchData = _productOptionManager.GetSearchData(query);
     viewData["product-options"] = productOptionSearchData.AttributeOptions;
     viewData["product-specifications"] = productOptionSearchData.SpecificationOptions;
     viewData["max-price"] = _productSearchIndexService.GetMaxPrice(query);
 }
Example #9
0
        public ColorPalette(ViewContext viewContext, IJavaScriptInitializer initializer, ViewDataDictionary viewData)
            : base(viewContext, initializer, viewData)
        {
            Palette = ColorPickerPalette.Basic;

            Columns = ColumnsDefault;
        }
Example #10
0
        public async Task RenderAsync_AsPartial_ActivatesViews_WithThePassedInViewContext()
        {
            // Arrange
            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());
            var page = new TestableRazorPage(v =>
            {
                // viewData is assigned to ViewContext by the activator
                Assert.Same(viewData, v.ViewContext.ViewData);
            });
            var activator = new Mock<IRazorPageActivator>();
            var view = new RazorView(Mock.Of<IRazorViewEngine>(),
                                     activator.Object,
                                     CreateViewStartProvider(),
                                     page,
                                     isPartial: true);

            var viewContext = CreateViewContext(view);
            var expectedWriter = viewContext.Writer;
            activator.Setup(a => a.Activate(page, It.IsAny<ViewContext>()))
                     .Callback((IRazorPage p, ViewContext c) =>
                     {
                         Assert.Same(c, viewContext);
                         c.ViewData = viewData;
                     })
                     .Verifiable();

            // Act
            await view.RenderAsync(viewContext);

            // Assert
            activator.Verify();
            Assert.Same(expectedWriter, viewContext.Writer);
        }
        private static void RenderPartial(HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer)
        {
            ViewDataDictionary newViewData;
            if (model == null)
            {
                newViewData = viewData == null ? new ViewDataDictionary(htmlHelper.ViewData) : new ViewDataDictionary(viewData);
            }
            else
            {
                newViewData = viewData == null ? new ViewDataDictionary(model) : new ViewDataDictionary(viewData) { Model = model };
            }

            var controller = htmlHelper.ViewContext.Controller as Controller;
            var viewEngineCollection = controller != null ? controller.ViewEngineCollection : ViewEngines.Engines;
            var newViewContext = new ViewContext(htmlHelper.ViewContext, htmlHelper.ViewContext.View, newViewData, htmlHelper.ViewContext.TempData, writer);
            var result = viewEngineCollection.FindPartialView(newViewContext, partialViewName);
            if (result.View != null)
            {
                result.View.Render(newViewContext, writer);
            }
            else
            {
                var locationsText = new StringBuilder();
                foreach (string location in result.SearchedLocations)
                {
                    locationsText.AppendLine();
                    locationsText.Append(location);
                }

                throw new InvalidOperationException("The partial view '{0}' was not found or no view engine supports the searched locations. The following locations were searched: {1}".Arrange(partialViewName, locationsText));
            }
        }
Example #12
0
        protected override void OnMetadataProcess(ModelMetadata meta, string name, ViewDataDictionary viewData, ControllerContext context)
        {
            base.OnMetadataProcess(meta, name, viewData, context);

            if (name.IsEmpty())
            {
                throw new Exception("Name from ControlFor is empty");
            }

            this.Name = name;

            if (meta.IsReadOnly)
            {
                this.ReadOnly = true;
            }

            if (this.FieldLabel.IsEmpty())
            {
                this.FieldLabel = meta.GetDisplayName();
            }

            if (this.Note.IsEmpty() && meta.Description.IsNotEmpty())
            {
                this.Note = meta.Description;
            }

            ModelState modelState;
            if (viewData.ModelState.TryGetValue(name, out modelState))
            {
                if (modelState.Errors.Count > 0)
                {
                    this.CustomConfig.Add(new ConfigItem("activeError", JSON.Serialize(modelState.Errors.Select(e => e.ErrorMessage)), ParameterMode.Raw));
                }
            }
        }
 public IList<ResourceListViewModel> Process(IList<Resource> resources, ViewDataDictionary viewdata, string tagName)
 {
     var resourceListViewModel = ResourceMapper.MapFromDomainListToListViewModel(resources);
     StoreTicksOfCreateTimeInViewData(resourceListViewModel, viewdata);
     viewdata["tagName"] = tagName;
     return resourceListViewModel;
 }
Example #14
0
		//
		// GET: /Test/

		public ActionResult Index()
		{
			StringWriter sw = new StringWriter();
			IFileSystem files = N2.Context.Current.Resolve<IFileSystem>();
			List<ContentRegistration> expressions = new List<ContentRegistration>();
			foreach (var file in files.GetFiles("~/Dinamico/Themes/Default/Views/ContentPages/").Where(f => f.Name.EndsWith(".cshtml")))
			{
				var cctx = new ControllerContext(ControllerContext.HttpContext, new RouteData(), new ContentPagesController());
				cctx.RouteData.Values.Add("controller", "DynamicPages");
				var v = ViewEngines.Engines.FindView(cctx, file.VirtualPath, null);

				if (v.View == null)
					sw.Write(string.Join(", ", v.SearchedLocations.ToArray()));
				else
				{
					var temp = new ContentPage();
					cctx.RequestContext.RouteData.ApplyCurrentPath(new N2.Web.PathData(temp));
					var vdd = new ViewDataDictionary { Model = temp };
					var re = new ContentRegistration(new DefinitionMap().GetOrCreateDefinition(typeof(ContentPage)).Clone());
					N2.Web.Mvc.Html.RegistrationExtensions.SetRegistrationExpression(cctx.HttpContext, re);
					v.View.Render(new ViewContext(cctx, v.View, vdd, new TempDataDictionary(), sw), sw);
					expressions.Add(re);
				}
			}
			return View(expressions);
		}
        public static void SetViewDataForDate(ViewDataDictionary ViewData)
        {
            List<string> genderList = new List<string>();
            genderList.Add("Male");
            genderList.Add("Female");
            SelectList list = new SelectList(genderList);
            ViewData["gender"] = list;

            int[] dayA = new int[31];

            for (int i = 0; i < 31; i++)
            {
                dayA[i] = i + 1;
            }

            int[] yearA = new int[100];

            for (int i = 0; i < 100; i++)
            {
                yearA[i] = DateTime.Now.Year - i;
            }

            SelectList daySL = new SelectList(dayA);
            ViewData["days"] = daySL;

            SelectList yearSL = new SelectList(yearA);
            ViewData["years"] = yearSL;
        }
Example #16
0
        public static string RenderViewToString(string controllerName, string viewName, object viewData, List<KeyValuePair<string, object>> additionalData)
        {
            var context = HttpContext.Current;
              var contextBase = new HttpContextWrapper(context);
              var routeData = new RouteData();
              routeData.Values.Add("controller", controllerName);

              var controllerContext = new ControllerContext(contextBase,
            routeData,
            new EmptyController());

              var razorViewEngine = new RazorViewEngine();
              var razorViewResult = razorViewEngine.FindView(controllerContext,
            viewName,
            "",
            false);

              ViewDataDictionary vdd = new ViewDataDictionary(viewData);
              if (additionalData != null && additionalData.Any())
            additionalData.ForEach(vdd.Add);

              var writer = new StringWriter();
              var viewContext = new ViewContext(controllerContext,
            razorViewResult.View,
            vdd,
            new TempDataDictionary(),
            writer);
              razorViewResult.View.Render(viewContext, writer);

              return writer.ToString();
        }
 private static ViewDataDictionary GetViewDataWithSelectList() {
     ViewDataDictionary viewData = new ViewDataDictionary();
     SelectList selectList = new SelectList(MultiSelectListTest.GetSampleAnonymousObjects(), "Letter", "FullWord", "C");
     viewData["foo"] = selectList;
     viewData["foo.bar"] = selectList;
     return viewData;
 }
Example #18
0
 public DatePicker(ViewContext viewContext, IJavaScriptInitializer initializer, ViewDataDictionary viewData)
     : base(viewContext, initializer, viewData)
 {
     Min = defaultMinDate;
     Max = defaultMaxDate;
     MonthTemplate = new MonthTemplate();
 }
Example #19
0
        public void PropertiesInitializedCorrectly()
        {
            // Arrange
            var viewData = new ViewDataDictionary<string>(new EmptyModelMetadataProvider());

            // Act & Assert
            Assert.Empty(viewData);
            Assert.Equal(0, viewData.Count);
            Assert.False(viewData.IsReadOnly);

            Assert.NotNull(viewData.Keys);
            Assert.Empty(viewData.Keys);

            Assert.Null(viewData.Model);
            Assert.NotNull(viewData.ModelMetadata);
            Assert.NotNull(viewData.ModelState);

            Assert.NotNull(viewData.TemplateInfo);
            Assert.Equal(0, viewData.TemplateInfo.TemplateDepth);
            Assert.Equal(string.Empty, viewData.TemplateInfo.FormattedModelValue);
            Assert.Equal(string.Empty, viewData.TemplateInfo.HtmlFieldPrefix);

            Assert.NotNull(viewData.Values);
            Assert.Empty(viewData.Values);
        }
        public void GuardClauses()
        {
            // Arrange
            var controllerContext = new Mock<ControllerContext>().Object;
            var view = new Mock<IView>().Object;
            var viewData = new ViewDataDictionary();
            var tempData = new TempDataDictionary();
            var writer = new StringWriter();

            // Act & Assert
            Assert.ThrowsArgumentNull(
                () => new ViewContext(null, view, viewData, tempData, writer),
                "controllerContext"
                );
            Assert.ThrowsArgumentNull(
                () => new ViewContext(controllerContext, null, viewData, tempData, writer),
                "view"
                );
            Assert.ThrowsArgumentNull(
                () => new ViewContext(controllerContext, view, null, tempData, writer),
                "viewData"
                );
            Assert.ThrowsArgumentNull(
                () => new ViewContext(controllerContext, view, viewData, null, writer),
                "tempData"
                );
            Assert.ThrowsArgumentNull(
                () => new ViewContext(controllerContext, view, viewData, tempData, null),
                "writer"
                );
        }
        public void DisplayNameConsultsMetadataProviderForMetadataAboutProperty()
        {
            // Arrange
            Model model = new Model { PropertyName = "propertyValue" };

            ViewDataDictionary viewData = new ViewDataDictionary();
            Mock<ViewContext> viewContext = new Mock<ViewContext>();
            viewContext.Setup(c => c.ViewData).Returns(viewData);

            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();
            viewDataContainer.Setup(c => c.ViewData).Returns(viewData);

            HtmlHelper<Model> html = new HtmlHelper<Model>(viewContext.Object, viewDataContainer.Object);
            viewData.Model = model;

            MetadataHelper metadataHelper = new MetadataHelper();

            metadataHelper.MetadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), typeof(Model), "PropertyName"))
                .Returns(metadataHelper.Metadata.Object)
                .Verifiable();

            // Act
            html.DisplayNameInternal("PropertyName", metadataHelper.MetadataProvider.Object);

            // Assert
            metadataHelper.MetadataProvider.Verify();
        }
        public void EvalReturnsSimplePropertyValue()
        {
            var obj = new { Foo = "Bar" };
            ViewDataDictionary vdd = new ViewDataDictionary(obj);

            Assert.Equal("Bar", vdd.Eval("Foo"));
        }
        public void EvalWithModelAndDictionaryPropertyEvaluatesDictionaryValue()
        {
            var obj = new { Foo = new Dictionary<string, object> { { "Bar", "Baz" } } };
            ViewDataDictionary vdd = new ViewDataDictionary(obj);

            Assert.Equal("Baz", vdd.Eval("Foo.Bar"));
        }
Example #24
0
        public void SettingViewData_AlsoUpdatesViewBag()
        {
            // Arrange (eventually passing null to these consturctors will throw)
            var context = new ViewContext(
                new ActionContext(null, null, null),
                view: null,
                viewData: null,
                tempData: null,
                writer: null,
                htmlHelperOptions: new HtmlHelperOptions());
            var originalViewData = context.ViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());
            var replacementViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());

            // Act
            context.ViewBag.Hello = "goodbye";
            context.ViewData = replacementViewData;
            context.ViewBag.Another = "property";

            // Assert
            Assert.NotSame(originalViewData, context.ViewData);
            Assert.Same(replacementViewData, context.ViewData);
            Assert.Null(context.ViewBag.Hello);
            Assert.Equal("property", context.ViewBag.Another);
            Assert.Equal("property", context.ViewData["Another"]);
        }
        public void Execute_ResolvesView_WithDefaultAsViewName()
        {
            // Arrange
            var view = new Mock<IView>(MockBehavior.Strict);
            view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>()))
                .Returns(Task.FromResult(result: true))
                .Verifiable();

            var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict);
            viewEngine.Setup(e => e.FindPartialView(It.IsAny<ActionContext>(), It.IsAny<string>()))
                      .Returns(ViewEngineResult.Found("Default", view.Object))
                      .Verifiable();

            var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

            var result = new ViewViewComponentResult
            {
                ViewEngine = viewEngine.Object,
                ViewData = viewData
            };

            var viewComponentContext = GetViewComponentContext(view.Object, viewData);

            // Act
            result.Execute(viewComponentContext);

            // Assert
            viewEngine.Verify();
            view.Verify();
        }
Example #26
0
 public static void RenderPartial(this AjaxHelper ajaxHelper,
                                  string partialViewName,
                                  object model = null,
                                  ViewDataDictionary viewData = null)
 {
     throw new NotImplementedException();
 }
Example #27
0
 public Sortable(ViewContext viewContext, IJavaScriptInitializer javaScriptInitializer, ViewDataDictionary viewData)
     : base(viewContext, javaScriptInitializer, viewData)
 {
     CursorOffset = new SortableCursorOffset();
     HintHandler = new ClientHandlerDescriptor();
     PlaceholderHandler = new ClientHandlerDescriptor();
 }
Example #28
0
 public BaseViewHelper(RequestContext requestContext, ViewContext viewContext, IViewDataContainer viewDataContainer, RouteCollection routeCollection)
 {
     ViewData = new ViewDataDictionary(viewDataContainer.ViewData);
     RequestContext = requestContext;
     ViewContext = viewContext;
     RouteCollection = routeCollection;
 }
Example #29
0
        public void SettingViewData_AlsoUpdatesViewBag()
        {
            // Arrange
            var originalViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());
            var context = new ViewContext(
                new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: originalViewData,
                tempData: new TempDataDictionary(new HttpContextAccessor(), Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var replacementViewData = new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider());

            // Act
            context.ViewBag.Hello = "goodbye";
            context.ViewData = replacementViewData;
            context.ViewBag.Another = "property";

            // Assert
            Assert.NotSame(originalViewData, context.ViewData);
            Assert.Same(replacementViewData, context.ViewData);
            Assert.Null(context.ViewBag.Hello);
            Assert.Equal("property", context.ViewBag.Another);
            Assert.Equal("property", context.ViewData["Another"]);
        }
 public static ViewDataDictionary Merge(this ViewDataDictionary source, ViewDataDictionary dic1)
 {
     if (dic1 != null)
     {
         foreach (KeyValuePair<string, object> pair in dic1)
         {
             if (!source.ContainsKey(pair.Key))
             {
                 source.Add(pair.Key, pair.Value);
             }
         }
         foreach (KeyValuePair<string, ModelState> pair2 in dic1.ModelState)
         {
             if (!source.ModelState.ContainsKey(pair2.Key))
             {
                 source.ModelState.Add(pair2.Key, pair2.Value);
             }
         }
         if (source.Model == null)
         {
             source.Model = dic1.Model;
         }
         if (source.TemplateInfo == null)
         {
             source.TemplateInfo = dic1.TemplateInfo;
         }
         if (source.ModelMetadata == null)
         {
             source.ModelMetadata = dic1.ModelMetadata;
         }
     }
     return source;
 }
Example #31
0
 public NumericTextBox(ViewContext viewContext, IJavaScriptInitializer javaScriptInitializer, ViewDataDictionary viewData)
     : base(viewContext, javaScriptInitializer, viewData)
 {
     Enabled = true;
 }
Example #32
0
        internal async Task RenderView(IRequest req, Stream stream, ViewDataDictionary viewData, IView view, string layout = null)
        {
            var razorView = view as RazorView;

            try
            {
                var actionContext = new ActionContext(
                    ((HttpRequest)req.OriginalRequest).HttpContext,
                    new RouteData(),
                    new ActionDescriptor());

                var sw = new StreamWriter(stream);
                {
                    if (viewData == null)
                    {
                        viewData = CreateViewData((object)null);
                    }

                    // Use "_Layout" if unspecified
                    if (razorView != null)
                    {
                        razorView.RazorPage.Layout = layout ?? DefaultLayout;
                    }

                    // Allows Layout from being overridden in page with: Layout = Html.ResolveLayout("LayoutUnlessOverridden")
                    if (layout != null)
                    {
                        viewData["Layout"] = layout;
                    }

                    viewData[Keywords.IRequest] = req;

                    var viewContext = new ViewContext(
                        actionContext,
                        view,
                        viewData,
                        new TempDataDictionary(actionContext.HttpContext, tempDataProvider),
                        sw,
                        new HtmlHelperOptions());

                    await view.RenderAsync(viewContext);

                    sw.Flush();

                    try
                    {
                        using (razorView?.RazorPage as IDisposable) { }
                    }
                    catch (Exception ex)
                    {
                        log.Warn("Error trying to dispose Razor View: " + ex.Message, ex);
                    }
                }
            }
            catch (StopExecutionException) { }
            catch (Exception ex)
            {
                req.Items[RenderException] = ex;
                //Can't set HTTP Headers which are already written at this point
                await req.Response.WriteErrorBody(ex);
            }
        }
 public static ModelMetadata ModelMetadata(this ViewDataDictionary viewData, object model, IModelMetadataProvider modelMetadataProvider)
 {
     return(ModelMetadata(model, modelMetadataProvider));
 }
Example #34
0
 public static void AddActivePage(this ViewDataDictionary viewData, string activePage) => viewData[ActivePageKey] = activePage;
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (String.IsNullOrEmpty(this.ViewName))
            {
                this.ViewName = context.RouteData.GetRequiredString("action");
            }

            string id = this.ControlId ?? BaseControl.GenerateId();
            string ct = this.ContainerId ?? "Ext.getBody()";

            ViewDataDictionary dict   = new ViewDataDictionary(this.ViewData);
            ViewEngineResult   result = null;

            if (this.View == null)
            {
                result    = this.ViewEngineCollection.FindPartialView(context, this.ViewName);
                this.View = result.View;
            }

            if (this.View is RazorView)
            {
                this.RenderRazorView(context, (RazorView)this.View);
                return;
            }

            string path = ((WebFormView)this.View).ViewPath;

            ViewContext viewContext = new ViewContext(context, this.View, this.ViewData, this.TempData, context.HttpContext.Response.Output);

            PartialViewPage pageHolder = new PartialViewPage
            {
                ViewData    = dict,
                ViewContext = viewContext
            };

            var curRM = HttpContext.Current.Items[typeof(ResourceManager)];

            HttpContext.Current.Items[typeof(ResourceManager)] = null;

            ResourceManager rm = new ResourceManager();

            rm.RenderScripts = ResourceLocationType.None;
            rm.RenderStyles  = ResourceLocationType.None;
            rm.IDMode        = this.IDMode;
            pageHolder.Controls.Add(rm);

            ViewUserControl uc = (ViewUserControl)pageHolder.LoadControl(path);

            uc.ID       = id + "_UC";
            uc.ViewData = ViewData;

            BaseControl controlToRender = null;

            if (this.ControlToRender.IsEmpty() && !this.SingleControl)
            {
                Panel p;
                if (this.PanelConfig != null)
                {
                    p        = new Panel(this.PanelConfig);
                    p.ID     = id;
                    p.IDMode = this.IDMode;
                }
                else
                {
                    p = new Panel {
                        ID = id, IDMode = this.IDMode, Border = false, PreventHeader = false
                    };
                }

                pageHolder.Controls.Add(p);
                p.ContentControls.Add(uc);
                controlToRender = p;
            }
            else
            {
                pageHolder.Controls.Add(uc);
                BaseControl c = null;

                if (this.SingleControl)
                {
                    c = Ext.Net.Utilities.ControlUtils.FindControl <BaseControl>(uc);
                }
                else
                {
                    c = Ext.Net.Utilities.ControlUtils.FindControl <BaseControl>(pageHolder, this.ControlToRender);
                }

                if (c == null)
                {
                    if (this.SingleControl)
                    {
                        throw new Exception("Cannot find the Ext.Net control in the view");
                    }
                    else
                    {
                        throw new Exception("Cannot find the control with ID=" + this.ControlToRender);
                    }
                }

                controlToRender = c;

                if (controlToRender.IDMode == IDMode.Inherit)
                {
                    controlToRender.IDMode = this.IDMode;
                }
            }

            pageHolder.InitHelpers();

            string script = controlToRender.ToScript(this.RenderMode, ct, true);

            HttpContext.Current.Items[typeof(ResourceManager)] = curRM;

            this.RenderScript(context, script);
        }
        public void Create_ReturnsEmptyView()
        {
            ViewDataDictionary actual = controller.Create().ViewData;

            Assert.Null(actual.Model);
        }
Example #37
0
        // caching version
        public static Tuple <string, IDictionary <string, object> > BlockWithCache(HtmlHelper helper, RenderingBlock block, ViewDataDictionary viewData)
        {
            // nothing?
            if (block == null)
            {
                return(null);
            }

            // get the current block model
            // BlockModel<TContent> : BlockModel
            var currentBlockModel = helper.ViewData.Model as BlockModel;

            if (currentBlockModel == null)
            {
                throw new Exception("Model does not inherit from BlockModel.");
            }

            var cacheMode = block.Cache == null
                ? CacheMode.Ignore
                : block.Cache.GetCacheMode(block, currentBlockModel.Content, viewData);

            if (block.Cache == null || cacheMode == CacheMode.Ignore) // test null again so ReSharper is happy
            {
                return(Block(helper, block, viewData));
            }

            var cache   = RunContext.RuntimeCache;
            var request = RunContext.IsTesting ? null : helper.ViewContext.HttpContext.Request; // todo: Environment.GetRequest(helper) OR mock request
            var key     = GetCacheKey(block, currentBlockModel.Content, request, viewData);

            // in order to refresh we have to flush before getting
            if (cacheMode == CacheMode.Refresh)
            {
                cache.ClearCacheByKeySearch(key);
            }

            var cached = (Tuple <string, IDictionary <String, object> >)cache.GetCacheItem(
                key,
                () => Block(helper, block, viewData),
                new TimeSpan(0, 0, 0, block.Cache.Duration), // duration
                false,                                       // sliding
                System.Web.Caching.CacheItemPriority.NotRemovable);

            return(cached);
        }
Example #38
0
        // basic, non-caching version
        private static Tuple <string, IDictionary <string, object> > Block(HtmlHelper helper, RenderingBlock block, ViewDataDictionary viewData)
        {
            // nothing?
            if (block == null)
            {
                return(null);
            }

            // get the current block model
            // BlockModel<TContent> : BlockModel
            var currentBlockModel = helper.ViewData.Model as BlockModel;

            if (currentBlockModel == null)
            {
                throw new Exception("Model does not inherit from BlockModel.");
            }

            var controller = BlockControllerBase.CreateController(helper, block, currentBlockModel.Content, currentBlockModel.CurrentCulture, viewData);
            var text       = controller.RenderInternal();
            var meta       = controller.Meta; // this is how we get it back...

            return(Tuple.Create(text, meta));

            // we have:
            //   UmbracoViewPage<TModel> : WebViewPage<TModel>
            //     Model is TModel and we know how to map
            //     IPublishedContent, RenderModel, RenderModel<TContent>
            //   UmbracoViewPage : UmbracoViewPage<IPublishedContent>
            //     Model is IPublishedContent
            //
            // and deprecating:
            //   UmbracoTemplatePage<TContent> : UmbracoViewPage<RenderModel<TContent>>
            //     Model is RenderModel<TContent> ie Content is TContent
            //   UmbracoTemplatePage : UmbracoViewPage<RenderModel>
            //     Model is RenderModel ie Content is IPublishedContent

            // UmbracoViewPage<TModel> can map from BlockModel or BlockModel<TContent>
            // because they inherit from RenderModel, and there is no way it can map
            // from anything to BlockModel so that's not an issue.
            // However it does not know how to map BlockModel to BlockModel<TContent>
            // and that is an issue. So it will fallback to using a TypeConverter, which
            // we implemented in BlockModelTypeConverter.
        }
Example #39
0
        private static string GetCacheKey(RenderingBlock block, IPublishedContent content, HttpRequestBase request, ViewDataDictionary viewData)
        {
            var key   = "Zbu.Blocks__" + block.Source;
            var cache = block.Cache;

            if (cache.ByPage)
            {
                key += "__p:" + content.Id;
            }
            if (!string.IsNullOrWhiteSpace(cache.ByConst))
            {
                key += "__c:" + cache.ByConst;
            }

            if (cache.ByMember)
            {
                // sure it's obsolete but what's the new way of getting the 'current' member ID?
                // currently even v7 HtmlHelperRenderExtensions uses the legacy API
                var member = Member.GetCurrentMember();
                key += "__m:" + (member == null ? 0 : member.Id);
            }

            if (cache.ByQueryString != null)
            {
                key = cache.ByQueryString.Aggregate(key, (current, vb) =>
                                                    current + "__" + request.QueryString[vb]);
            }

            if (cache.ByProperty != null)
            {
                key = cache.ByProperty.Aggregate(key, (current, alias) =>
                {
                    var recurse = alias.StartsWith("_");
                    var value   = content.GetPropertyValue(recurse ? alias.Substring(1) : alias, recurse);
                    return(current + "__v:" + value);
                });
            }

            var custom = cache.GetCacheCustom(request, block, content, viewData);

            if (!string.IsNullOrWhiteSpace(custom))
            {
                key += "__x:" + custom;
            }

            return(key.ToLowerInvariant());
        }
Example #40
0
 public ViewDataContainer(ViewDataDictionary viewData)
 {
     ViewData = viewData;
 }
Example #41
0
        /// <summary>
        /// Generates a data collection for the files in the data folder
        /// </summary>
        /// <returns>The data collection for Pattern Lab</returns>
        public ViewDataDictionary Data()
        {
            // Return cached value if set
            if (_data != null)
            {
                return(_data);
            }

            var host = Dns.GetHostEntry(Dns.GetHostName());

            // Get local IP address
            var ipAddresses = host.AddressList;
            var ipAddress   = ipAddresses[ipAddresses.Length - 1].ToString();

            // Identify hidden ish controls from config
            var ishSettings = Setting("ishControlsHide")
                              .Split(new[] { IdentifierDelimiter }, StringSplitOptions.RemoveEmptyEntries);
            var hiddenIshControls = ishSettings.ToDictionary(s => s.Trim(), s => true);

            // Hide the 'Page follow' ish control if disabled in config
            if (Setting("pageFollowNav").Equals("false", StringComparison.InvariantCultureIgnoreCase))
            {
                hiddenIshControls.Add("tools-follow", true);
            }
            else
            {
                // TODO: #24 Implement page follow from PHP version. Currently always hidden. Delete this else statement once implemented
                hiddenIshControls.Add("tools-follow", true);
            }

            // Hide the 'Auto-reload' ish control if disabled in config
            if (Setting("autoReloadNav").Equals("false", StringComparison.InvariantCultureIgnoreCase))
            {
                hiddenIshControls.Add("tools-reload", true);
            }
            else
            {
                // TODO: #23 Implement page auto-reload from PHP version. Currently always hidden. Delete this else statement once implemented
                hiddenIshControls.Add("tools-reload", true);
            }

            var patternLinks = new Dictionary <string, string>();
            var patternPaths = new Dictionary <string, object>();
            var viewAllPaths = new Dictionary <string, object>();
            var patternTypes = new List <object>();

            // Use all patterns that aren't hidden
            var patterns =
                Patterns()
                .Where(p => !p.Hidden)
                .ToList();

            if (patterns.Any())
            {
                // Get a list of distinct types
                var types = patterns.Select(p => p.Type).Distinct().ToList();
                foreach (var type in types)
                {
                    var typeName        = type.StripOrdinals();
                    var typeDisplayName = typeName.ToDisplayCase();

                    // Create JSON object to hold information about the current type
                    var typeDetails =
                        new
                    {
                        patternTypeLC    = typeName,
                        patternTypeUC    = typeDisplayName,
                        patternTypeItems = new List <object>(),
                        patternItems     = new List <object>()
                    };

                    // Get patterns that match the current type (e.g. Atoms)
                    var typedPatterns =
                        patterns.Where(p => p.Type.Equals(type, StringComparison.InvariantCultureIgnoreCase)).ToList();

                    // Get the sub-types from the patterns that match the current type (e.g. Global, under Atoms)
                    var subTypes =
                        typedPatterns.Select(p => p.SubType).Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();

                    var typedPatternPaths = new Dictionary <string, string>();
                    var subTypePaths      = new Dictionary <string, string>();

                    if (subTypes.Any())
                    {
                        foreach (var subType in subTypes)
                        {
                            var subTypeName        = subType.StripOrdinals();
                            var subTypeDisplayName = subTypeName.ToDisplayCase();
                            var subTypePath        = string.Format("{0}-{1}", type, subType);

                            // Create JSON object to hold information about the current sub-type
                            var subTypeDetails = new
                            {
                                patternSubtypeLC    = subTypeName,
                                patternSubtypeUC    = subTypeDisplayName,
                                patternSubtypeItems = new List <object>()
                            };

                            // Find all patterns that match the current type, and sub-type
                            var subTypedPatterns =
                                patterns.Where(
                                    p =>
                                    p.Type.Equals(type, StringComparison.InvariantCultureIgnoreCase) &&
                                    p.SubType.Equals(subType, StringComparison.InvariantCultureIgnoreCase)).ToList();

                            foreach (var pattern in subTypedPatterns)
                            {
                                // Create JSON object to hold information about the pattern and add to sub-type JSON
                                subTypeDetails.patternSubtypeItems.Add(
                                    new
                                {
                                    patternPath    = pattern.HtmlUrl,
                                    patternState   = GetState(pattern),
                                    patternPartial = pattern.Partial,
                                    patternName    = pattern.Name.StripOrdinals().ToDisplayCase()
                                });
                            }

                            // Add a 'View all' JSON object for use in the navigation
                            subTypeDetails.patternSubtypeItems.Add(
                                new
                            {
                                patternPath    = string.Format("{0}/{1}", subTypePath, FileNameViewer),
                                patternPartial =
                                    string.Format("{0}-{1}-{2}", ViewNameViewAllPage, typeName, subTypeName),
                                patternName = "View All"
                            });

                            // Add sub-type JSON object to the type JSON object
                            typeDetails.patternTypeItems.Add(subTypeDetails);

                            if (!subTypePaths.ContainsKey(subTypeName))
                            {
                                // Handle duplicate sub-type names
                                subTypePaths.Add(subTypeName, subTypePath);
                            }
                        }
                    }

                    foreach (var pattern in typedPatterns)
                    {
                        var patternName = pattern.Name.StripOrdinals();

                        if (!patternLinks.ContainsKey(pattern.Partial))
                        {
                            // Build list of link variables - http://patternlab.io/docs/data-link-variable.html
                            patternLinks.Add(pattern.Partial,
                                             string.Format("../../{0}/{1}", FolderNamePattern.TrimStart(IdentifierHidden),
                                                           pattern.HtmlUrl));
                        }

                        if (!typedPatternPaths.ContainsKey(patternName))
                        {
                            // Build list of pattern paths for footer
                            typedPatternPaths.Add(patternName, pattern.PathDash);
                        }

                        if (!subTypes.Any())
                        {
                            // Create JSON object for data required by footer
                            typeDetails.patternItems.Add(
                                new
                            {
                                patternPath    = pattern.HtmlUrl,
                                patternState   = GetState(pattern),
                                patternPartial = pattern.Partial,
                                patternName    = pattern.Name.StripOrdinals().ToDisplayCase()
                            });
                        }
                    }

                    patternPaths.Add(typeName, typedPatternPaths);
                    viewAllPaths.Add(typeName, subTypePaths);
                    patternTypes.Add(typeDetails);
                }
            }

            // Get the media queries used by the patterns
            var mediaQueries = GetMediaQueries();

            var serializer = new JavaScriptSerializer();

            // Pass config settings and collections of pattern data to a new data collection
            _data = new ViewDataDictionary
            {
                { "ishminimum", Setting("ishMinimum") },
                { "ishmaximum", Setting("ishMaximum") },
                { "qrcodegeneratoron", Setting("qrCodeGeneratorOn") },
                { "ipaddress", ipAddress },
                { "xiphostname", Setting("xipHostname") },
                { "autoreloadnav", Setting("autoReloadNav") },
                { "autoreloadport", Setting("autoReloadPort") },
                { "pagefollownav", Setting("pageFollowNav") },
                { "pagefollowport", Setting("pageFollowPort") },
                { "ishControlsHide", hiddenIshControls },
                { "link", patternLinks },
                { "patternpaths", serializer.Serialize(patternPaths) },
                { "viewallpaths", serializer.Serialize(viewAllPaths) },
                { "mqs", mediaQueries },
                { "patternTypes", patternTypes }
            };

            var root = new DirectoryInfo(Path.Combine(HttpRuntime.AppDomainAppPath, FolderNameData));

            // Find any data files in the data folder and add these to the data collection
            var dataFiles = root.GetFiles(string.Concat("*", FileExtensionData), SearchOption.AllDirectories);

            _data = AppendData(_data, dataFiles);

            // Return the combined data collection
            return(_data);
        }
 //Model Type
 public static Type ModelType(this ViewDataDictionary viewData)
 {
     return(ModelType(viewData.Model));
 }
Example #43
0
        public static HtmlHelper <TModel> For <TModel>(ViewContext viewContext, ViewDataDictionary viewData, RouteCollection routeCollection) where TModel : class, new()
        {
            TModel model = new TModel();

            return(For <TModel>(viewContext, viewData, routeCollection, model));
        }
Example #44
0
 /// <summary>
 /// Combines a data collection and the contents of a data file
 /// </summary>
 /// <param name="original">The original data collection</param>
 /// <param name="dataFile">The data file</param>
 /// <returns>The combined data collection</returns>
 public static ViewDataDictionary AppendData(ViewDataDictionary original, FileInfo dataFile)
 {
     // Create new list of data files and append to collection
     return(dataFile != null?AppendData(original, new[] { dataFile }) : original);
 }
Example #45
0
        public static ModelExplorer FromLambdaExpression <TModel, TResult>(
            [NotNull] Expression <Func <TModel, TResult> > expression,
            [NotNull] ViewDataDictionary <TModel> viewData,
            IModelMetadataProvider metadataProvider)
        {
            string propertyName    = null;
            Type   containerType   = null;
            var    legalExpression = false;

            // Need to verify the expression is valid; it needs to at least end in something
            // that we can convert to a meaningful string for model binding purposes

            switch (expression.Body.NodeType)
            {
            case ExpressionType.ArrayIndex:
                // ArrayIndex always means a single-dimensional indexer;
                // multi-dimensional indexer is a method call to Get().
                legalExpression = true;
                break;

            case ExpressionType.Call:
                // Only legal method call is a single argument indexer/DefaultMember call
                legalExpression = ExpressionHelper.IsSingleArgumentIndexer(expression.Body);
                break;

            case ExpressionType.MemberAccess:
                // Property/field access is always legal
                var memberExpression = (MemberExpression)expression.Body;
                propertyName    = memberExpression.Member is PropertyInfo ? memberExpression.Member.Name : null;
                containerType   = memberExpression.Expression.Type;
                legalExpression = true;
                break;

            case ExpressionType.Parameter:
                // Parameter expression means "model => model", so we delegate to FromModel
                return(FromModel(viewData, metadataProvider));
            }

            if (!legalExpression)
            {
                throw new InvalidOperationException(Resources.TemplateHelpers_TemplateLimitations);
            }

            Func <object, object> modelAccessor = (container) =>
            {
                try
                {
                    return(CachedExpressionCompiler.Process(expression)((TModel)container));
                }
                catch (NullReferenceException)
                {
                    return(null);
                }
            };

            ModelMetadata metadata;

            if (propertyName == null)
            {
                // Ex:
                //    m => 5 (arbitrary expression)
                //    m => foo (arbitrary expression)
                //    m => m.Widgets[0] (expression ending with non-property-access)
                metadata = metadataProvider.GetMetadataForType(typeof(TResult));
            }
            else
            {
                // Ex:
                //    m => m.Color (simple property access)
                //    m => m.Color.Red (nested property access)
                //    m => m.Widgets[0].Size (expression ending with property-access)
                metadata = metadataProvider.GetMetadataForType(containerType).Properties[propertyName];
            }

            return(viewData.ModelExplorer.GetExplorerForExpression(metadata, modelAccessor));
        }
Example #46
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ProxyViewDataFeature" /> class.
 /// </summary>
 public ProxyViewDataFeature(ViewDataDictionary viewData, ITempDataDictionary tempData)
 {
     ViewData = viewData;
     TempData = tempData;
 }
Example #47
0
        public string RenderPartialToString(ControllerContext controllerContext, string p, ViewDataDictionary ViewData, TempDataDictionary TempData)
        {
            ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, p);

            if (result.View != null)
            {
                StringBuilder sb = new StringBuilder();
                using (StringWriter sw = new StringWriter(sb))
                {
                    using (HtmlTextWriter output = new HtmlTextWriter(sw))
                    {
                        ViewContext viewContext = new ViewContext(controllerContext, result.View, ViewData, TempData, output);
                        result.View.Render(viewContext, output);
                    }
                }

                return(sb.ToString());
            }
            return(String.Empty);
        }
Example #48
0
 public override void SetViewData(ISession session, ViewDataDictionary viewDataDictionary)
 {
     viewDataDictionary["DefaultCategoryOptions"] = _siteSettingsOptionGenerator.GetMediaCategoryOptions(session, null);
     viewDataDictionary["CacheExpiryTypeOptions"] = _siteSettingsOptionGenerator.GetCacheExpiryTypeOptions();
 }
Example #49
0
        private static string name <T>(this ViewDataDictionary <T> model, Expression <Func <T, object> > lambda)
        {
            string description = ModelMetadata.FromLambdaExpression(lambda, model).PropertyName;

            return(description);
        }
Example #50
0
 /// <summary>Create an Email where the ViewName is derived from the name of the class.</summary>
 /// <remarks>Used when defining strongly typed Email classes.</remarks>
 protected Email()
 {
     Attachments = new List <Attachment>();
     ViewName    = DeriveViewNameFromClassName();
     ViewData    = new ViewDataDictionary(this);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="viewName"></param>
        /// <param name="viewData"></param>
        /// <param name="model"></param>
        /// <param name="tempData"></param>
        /// <param name="idMode"></param>
        /// <param name="controlId"></param>
        /// <returns></returns>
        public virtual string Render(ControllerContext context, string viewName, ViewDataDictionary viewData, object model, TempDataDictionary tempData, IDMode idMode, string controlId)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (String.IsNullOrEmpty(viewName))
            {
                viewName = context.RouteData.GetRequiredString("action");
            }

            //string path = PartialViewResult.FindView(context, viewName);
            string id = controlId ?? "ID_" + Guid.NewGuid().ToString().Replace("-", "");
            string ct = "ID_" + Guid.NewGuid().ToString().Replace("-", "");

            ViewDataDictionary newViewData = null;

            if (model == null)
            {
                if (viewData == null)
                {
                    newViewData = new ViewDataDictionary();
                }
                else
                {
                    newViewData = new ViewDataDictionary(viewData);
                }
            }
            else
            {
                if (viewData == null)
                {
                    newViewData = new ViewDataDictionary(model);
                }
                else
                {
                    newViewData = new ViewDataDictionary(viewData)
                    {
                        Model = model
                    };
                }
            }

            ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, viewName);
            IView            view   = result.View;
            string           path   = ((WebFormView)view).ViewPath;

            ViewContext viewContext = new ViewContext(context, view, newViewData, tempData ?? new TempDataDictionary(), context.HttpContext.Response.Output);

            PartialViewPage pageHolder = new PartialViewPage
            {
                ViewData    = newViewData,
                ViewContext = viewContext
            };

            var curRM = HttpContext.Current.Items[typeof(ResourceManager)];

            HttpContext.Current.Items[typeof(ResourceManager)] = null;
            object oldPageRM = null;

            if (context.HttpContext.CurrentHandler is Page)
            {
                oldPageRM = ((Page)HttpContext.Current.CurrentHandler).Items[typeof(ResourceManager)];
                ((Page)HttpContext.Current.CurrentHandler).Items[typeof(ResourceManager)] = null;
            }

            ResourceManager rm = new ResourceManager();

            rm.RenderScripts = ResourceLocationType.None;
            rm.RenderStyles  = ResourceLocationType.None;
            rm.IDMode        = idMode;
            pageHolder.Controls.Add(rm);
            Panel p = new Panel {
                ID = id, IDMode = idMode, Border = false, Header = false
            };

            pageHolder.Controls.Add(p);

            ViewUserControl uc = (ViewUserControl)pageHolder.LoadControl(path);

            uc.ID       = id + "_UC";
            uc.ViewData = newViewData;
            p.ContentControls.Add(uc);

            pageHolder.InitHelpers();

            string wScript = DefaultScriptBuilder.Create(p).Build(RenderMode.RenderTo, ct, null, true, true);
            string script  = string.Format("<div id=\"{0}\"></div><script type=\"text/javascript\">Ext.onReady(function(){{{1}}});</script>", ct, wScript);

            IDisposable disposable = view as IDisposable;

            if (disposable != null)
            {
                disposable.Dispose();
            }

            HttpContext.Current.Items[typeof(ResourceManager)] = curRM;
            if (context.HttpContext.CurrentHandler is Page)
            {
                ((Page)HttpContext.Current.CurrentHandler).Items[typeof(ResourceManager)] = oldPageRM;
            }

            return(script);
        }
Example #52
0
        public virtual async Task ExecuteAsync(ActionContext context, ViewComponentResult viewComponentResult)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (viewComponentResult == null)
            {
                throw new ArgumentNullException(nameof(viewComponentResult));
            }

            var response = context.HttpContext.Response;

            var viewData = viewComponentResult.ViewData;

            if (viewData == null)
            {
                viewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
            }

            var tempData = viewComponentResult.TempData;

            if (tempData == null)
            {
                tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
            }

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                viewComponentResult.ContentType,
                response.ContentType,
                ViewExecutor.DefaultContentType,
                out var resolvedContentType,
                out var resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (viewComponentResult.StatusCode != null)
            {
                response.StatusCode = viewComponentResult.StatusCode.Value;
            }

            using (var writer = new HttpResponseStreamWriter(response.Body, resolvedContentTypeEncoding))
            {
                var viewContext = new ViewContext(
                    context,
                    NullView.Instance,
                    viewData,
                    tempData,
                    writer,
                    _htmlHelperOptions);

                // IViewComponentHelper is stateful, we want to make sure to retrieve it every time we need it.
                var viewComponentHelper = context.HttpContext.RequestServices.GetRequiredService <IViewComponentHelper>();
                (viewComponentHelper as IViewContextAware)?.Contextualize(viewContext);

                var result = await GetViewComponentResult(viewComponentHelper, _logger, viewComponentResult);

                result.WriteTo(writer, _htmlEncoder);
            }
        }
Example #53
0
        /// <summary>
        /// Renders a partial view that is found in the specified area
        /// </summary>
        public static IHtmlContent AreaPartial(this IHtmlHelper helper, string partial, string area, object model = null, ViewDataDictionary viewData = null)
        {
            var originalArea = helper.ViewContext.RouteData.DataTokens["area"];

            helper.ViewContext.RouteData.DataTokens["area"] = area;
            var result = helper.Partial(partial, model, viewData);

            helper.ViewContext.RouteData.DataTokens["area"] = originalArea;
            return(result);
        }
 private string?GetAttemptedFieldValue(ViewDataDictionary viewData)
 {
     return(viewData.GetAttemptedValue(FormDateField.ToString()));
 }
Example #55
0
 public abstract void Init(IRazorViewEngine viewEngine, ViewDataDictionary viewData, IHttpRequest httpReq, IHttpResponse httpRes);
 /// <summary>
 ///
 /// </summary>
 /// <param name="context"></param>
 /// <param name="viewName"></param>
 /// <param name="viewData"></param>
 /// <param name="model"></param>
 /// <param name="idMode"></param>
 /// <param name="controlId"></param>
 /// <returns></returns>
 public virtual string Render(ControllerContext context, string viewName, ViewDataDictionary viewData, object model, IDMode idMode, string controlId)
 {
     return(this.Render(context, viewName, viewData, model, new TempDataDictionary(), idMode, controlId));
 }
Example #57
0
 protected BaseView()
 {
     ViewData = new ViewDataDictionary();
 }
Example #58
0
 public Tooltip(ViewContext viewContext, IJavaScriptInitializer javaScriptInitializer, ViewDataDictionary viewData)
     : base(viewContext, javaScriptInitializer, viewData)
 {
     Callout        = true;
     AutoHide       = true;
     ContentHandler = new ClientHandlerDescriptor();
     Animation      = new PopupAnimation();
 }
Example #59
0
        public static void SetViewState(this ViewDataDictionary dict, string key, object value)
        {
            var viewState = dict.GetViewState();

            viewState[key] = value;
        }
Example #60
0
 public ActionResult Index(CustomErrorModel cem)
 {
     ViewData = new ViewDataDictionary <CustomErrorModel>(cem);
     return(View());
 }