• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ViewContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ViewContext的典型用法代码示例。如果您正苦于以下问题:C# ViewContext类的具体用法?C# ViewContext怎么用?C# ViewContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ViewContext类属于命名空间,在下文中一共展示了ViewContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetBreadcrumb

        public IEnumerable<MvcSiteMapNode> GetBreadcrumb(ViewContext context)
        {
            String area = context.RouteData.Values["area"] as String;
            String action = context.RouteData.Values["action"] as String;
            String controller = context.RouteData.Values["controller"] as String;

            MvcSiteMapNode current = NodeList.SingleOrDefault(node =>
                String.Equals(node.Area, area, StringComparison.OrdinalIgnoreCase) &&
                String.Equals(node.Action, action, StringComparison.OrdinalIgnoreCase) &&
                String.Equals(node.Controller, controller, StringComparison.OrdinalIgnoreCase));

            List<MvcSiteMapNode> breadcrumb = new List<MvcSiteMapNode>();
            while (current != null)
            {
                breadcrumb.Insert(0, new MvcSiteMapNode
                {
                    IconClass = current.IconClass,

                    Controller = current.Controller,
                    Action = current.Action,
                    Area = current.Area
                });

                current = current.Parent;
            }

            return breadcrumb;
        }
开发者ID:NonFactors,项目名称:MVC6.Template,代码行数:28,代码来源:MvcSiteMapProvider.cs


示例2: ChildActionExtensionsTest

        public ChildActionExtensionsTest()
        {
            route = new Mock<RouteBase>();
            route.Setup(r => r.GetVirtualPath(It.IsAny<RequestContext>(), It.IsAny<RouteValueDictionary>()))
                .Returns(() => virtualPathData);

            virtualPathData = new VirtualPathData(route.Object, "~/VirtualPath");

            routes = new RouteCollection();
            routes.Add(route.Object);

            originalRouteData = new RouteData();

            string returnValue = "";
            httpContext = new Mock<HttpContextBase>();
            httpContext.Setup(hc => hc.Request.ApplicationPath).Returns("~");
            httpContext.Setup(hc => hc.Response.ApplyAppPathModifier(It.IsAny<string>()))
                .Callback<string>(s => returnValue = s)
                .Returns(() => returnValue);
            httpContext.Setup(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()));

            viewContext = new ViewContext
            {
                RequestContext = new RequestContext(httpContext.Object, originalRouteData)
            };

            viewDataContainer = new Mock<IViewDataContainer>();

            htmlHelper = new Mock<HtmlHelper>(viewContext, viewDataContainer.Object, routes);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:30,代码来源:ChildActionExtensionsTest.cs


示例3: RenderPartialViewToString

 protected string RenderPartialViewToString(string viewName, object model)
 {
     if (string.IsNullOrEmpty(viewName))
     {
         viewName = ControllerContext.ActionDescriptor.ActionName;
     }
     ViewData.Model = model;
     using (StringWriter sw = new StringWriter())
     {
         var engine = _serviceProvider.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
         // Resolver.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
         ViewEngineResult viewResult = engine.FindView(ControllerContext, viewName, false);
         ViewContext viewContext = new ViewContext(
                               ControllerContext,
                               viewResult.View,
                               ViewData,
                               TempData,
                               sw,
                               new HtmlHelperOptions() //Added this parameter in
                               );
         //Everything is async now!
         var t = viewResult.View.RenderAsync(viewContext);
         t.Wait();
         return sw.GetStringBuilder().ToString();
     }
 }
开发者ID:ChavFDG,项目名称:Stolons,代码行数:26,代码来源:BaseController.cs


示例4: PropertiesAreSet

        public void PropertiesAreSet()
        {
            // Arrange
            var mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Setup(o => o.HttpContext.Items).Returns(new Hashtable());
            var view = new Mock<IView>().Object;
            var viewData = new ViewDataDictionary();
            var tempData = new TempDataDictionary();
            var writer = new StringWriter();

            // Act
            ViewContext viewContext = new ViewContext(mockControllerContext.Object, view, viewData, tempData, writer);

            // Setting FormContext to null will return the default one later
            viewContext.FormContext = null;

            // Assert
            Assert.Equal(view, viewContext.View);
            Assert.Equal(viewData, viewContext.ViewData);
            Assert.Equal(tempData, viewContext.TempData);
            Assert.Equal(writer, viewContext.Writer);
            Assert.False(viewContext.UnobtrusiveJavaScriptEnabled); // Unobtrusive JavaScript should be off by default
            Assert.NotNull(viewContext.FormContext); // We get the default FormContext
            Assert.Equal("span", viewContext.ValidationSummaryMessageElement); // gen a <span/> by default
            Assert.Equal("span", viewContext.ValidationMessageElement); // gen a <span/> by default
        }
开发者ID:ahmetgoktas,项目名称:aspnetwebstack,代码行数:26,代码来源:ViewContextTest.cs


示例5: ExecuteAsync

        /// <inheritdoc />
        public async Task ExecuteAsync(WidgetContext context)
        {
            var viewEngine = ViewEngine ?? ResolveViewEngine(context);
            var viewData = ViewData ?? context.ViewData;
            bool isNullOrEmptyViewName = string.IsNullOrEmpty(ViewName);

            string state = null; // TODO: Resolve from value provider?

            string qualifiedViewName;
            if (!isNullOrEmptyViewName && (ViewName[0] == '~' || ViewName[0] == '/'))
            {
                qualifiedViewName = ViewName;
            }
            else
            {
                qualifiedViewName = string.Format(ViewPath, context.WidgetDescriptor.ShortName, isNullOrEmptyViewName ? (state ?? DefaultViewName) : ViewName);
            }

            var view = FindView(context.ViewContext, viewEngine, qualifiedViewName);
            var childViewContext = new ViewContext(
                context.ViewContext,
                view,
                viewData,
                context.Writer);

            using (view as IDisposable)
            {
                await view.RenderAsync(childViewContext);
            }
        }
开发者ID:Antaris,项目名称:AspNetCore.Mvc.Widgets,代码行数:31,代码来源:ViewWidgetResult.cs


示例6: DefaultForContext

 private string DefaultForContext(ViewContext context)
 {
     if (context == ViewContext.Edit)
         return Catalog.GetString ("Edit");
     // Don't care otherwise, Tags sounds reasonable
     return Catalog.GetString ("Tags");
 }
开发者ID:iainlane,项目名称:f-spot,代码行数:7,代码来源:Sidebar.cs


示例7: RenderViewUserControl

		private void RenderViewUserControl(ViewContext context, 
			TextWriter writer, ViewUserControl control)
		{
			control.ViewData = context.ViewData;
			control.Output = writer;
			control.RenderView(context);
		}
开发者ID:radischevo,项目名称:Radischevo.Wahha,代码行数:7,代码来源:WebFormView.cs


示例8: RenderView

		public override void RenderView(ViewContext viewContext)
		{
			var prevHandler = this.Context.Handler;
			var isOnAspx = prevHandler is Page;

			this.Controls.Add(new Placeholder() { Key = key });
			if (!isOnAspx)
			{
				this.Controls.Add(new SitecoreForm());
			}
			using (var containerPage = new PageHolderContainerPage(this))
			{
				try
				{
					if (!isOnAspx)
						this.Context.Handler = containerPage;
					if (global::Sitecore.Context.Page == null)
					{
						viewContext.Writer.WriteLine("<!-- Unable to use sitecoreplacholder outside sitecore -->");
						return;
					}
					InitializePageContext(containerPage, viewContext);
					RenderViewAndRestoreContentType(containerPage, viewContext);
				}
				finally
				{
					this.Context.Handler = prevHandler;
				}
			}
		}
开发者ID:bplasmeijer,项目名称:BoC.Sitecore.MVC,代码行数:30,代码来源:HtmlHelperExtensions.cs


示例9: InitializePageContext

		internal static void InitializePageContext(Page containerPage, ViewContext viewContext)
		{

			PageContext pageContext = global::Sitecore.Context.Page;
			if (pageContext == null)
				return;

			var exists = pageContext.Renderings != null && pageContext.Renderings.Count > 0;
			if (!exists)
			{
				//use the default initializer:
				pageContextInitializer.Invoke(pageContext, null);
				//viewContext.HttpContext.Items["_SITECORE_PLACEHOLDER_AVAILABLE"] = true;
			}
			else
			{
				//our own initializer (almost same as Initialize in PageContext, but we need to skip buildcontroltree, since that is already availabe)
				pageContext_page.SetValue(pageContext, containerPage);
				containerPage.PreRender += (sender, args) => pageContextOnPreRender.Invoke(pageContext, new[] {sender, args});
				switch (Settings.LayoutPageEvent)
				{
					case "preInit":
						containerPage.PreInit += (o, args) => pageContext.Build();
						break;
					case "init":
						containerPage.Init += (o, args) => pageContext.Build();
						break;
					case "load":
						containerPage.Load += (o, args) => pageContext.Build();
						break;
				}
			}
		}
开发者ID:bplasmeijer,项目名称:BoC.Sitecore.MVC,代码行数:33,代码来源:HtmlHelperExtensions.cs


示例10: ExecuteAsync

        /// <summary>
        /// Asynchronously renders the specified <paramref name="view"/> to the response body.
        /// </summary>
        /// <param name="view">The <see cref="IView"/> to render.</param>
        /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns>
        public static async Task ExecuteAsync([NotNull] IView view,
                                              [NotNull] ActionContext actionContext,
                                              [NotNull] ViewDataDictionary viewData,
                                              [NotNull] ITempDataDictionary tempData,
                                              [NotNull] HtmlHelperOptions htmlHelperOptions,
                                              MediaTypeHeaderValue contentType)
        {
            var response = actionContext.HttpContext.Response;

            contentType = contentType ?? DefaultContentType;
            if (contentType.Encoding == null)
            {
                // Do not modify the user supplied content type, so copy it instead
                contentType = contentType.Copy();
                contentType.Encoding = Encoding.UTF8;
            }

            response.ContentType = contentType.ToString();

            using (var writer = new HttpResponseStreamWriter(response.Body, contentType.Encoding))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    tempData,
                    writer,
                    htmlHelperOptions);

                await view.RenderAsync(viewContext);
            }
        }
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:40,代码来源:ViewExecutor.cs


示例11: UnobtrusiveFormContext

 public UnobtrusiveFormContext(ViewContext context, string formId)
 {
     _context = context;
     _context.ClientValidationEnabled = true;
     _context.UnobtrusiveJavaScriptEnabled = true;
     _context.FormContext = new FormContext { FormId = formId };
 }
开发者ID:Gutek,项目名称:Library,代码行数:7,代码来源:UnobtrusiveFormContext.cs


示例12: ViewLocalizer_UseIndexer_ReturnsLocalizedHtmlString

        public void ViewLocalizer_UseIndexer_ReturnsLocalizedHtmlString()
        {
            // Arrange
            var hostingEnvironment = new Mock<IHostingEnvironment>();
            hostingEnvironment.Setup(a => a.ApplicationName).Returns("TestApplication");

            var localizedString = new LocalizedHtmlString("Hello", "Bonjour");

            var htmlLocalizer = new Mock<IHtmlLocalizer>();
            htmlLocalizer.Setup(h => h["Hello"]).Returns(localizedString);

            var htmlLocalizerFactory = new Mock<IHtmlLocalizerFactory>();
            htmlLocalizerFactory.Setup(h => h.Create("TestApplication.example", "TestApplication"))
                .Returns(htmlLocalizer.Object);

            var viewLocalizer = new ViewLocalizer(htmlLocalizerFactory.Object, hostingEnvironment.Object);

            var view = new Mock<IView>();
            view.Setup(v => v.Path).Returns("example");
            var viewContext = new ViewContext();
            viewContext.View = view.Object;

            viewLocalizer.Contextualize(viewContext);

            // Act
            var actualLocalizedString = viewLocalizer["Hello"];

            // Assert
            Assert.Equal(localizedString, actualLocalizedString);
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:30,代码来源:ViewLocalizerTest.cs


示例13: CreateHelper

 public dynamic CreateHelper(ViewContext viewContext)
 {
     return new DisplayHelper(
         _displayManager,
         _shapeFactory,
         viewContext);
 }
开发者ID:jchenga,项目名称:Orchard2,代码行数:7,代码来源:DisplayHelperFactory.cs


示例14: RenderPartialViewToString

    /// <summary>
    /// Renders the specified partial view to a string.
    /// </summary>
    /// <param name="viewName">The name of the partial view.</param>
    /// <param name="model">The model.</param>
    /// <returns>The partial view as a string.</returns>
    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = ControllerContext.RouteData.GetRequiredString("action");
        }

        ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            // Find the partial view by its name and the current controller context.
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);

            if (viewResult.View == null)
            {
              throw new ArgumentException(string.Format("Could not find the view with the specified name '{0}'.", viewName), "viewName");
            }

            // Create a view context.
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

            // Render the view using the StringWriter object.
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
开发者ID:henkmollema,项目名称:MvcPartialViewToString,代码行数:34,代码来源:BaseController.cs


示例15: AddTo

 public Control AddTo(Control container, ViewContext context)
 {
     Literal l = new Literal();
     l.Text = context.Fragment.Value.Substring(1, context.Fragment.Value.Length - 2);
     container.Controls.Add(l);
     return l;
 }
开发者ID:sergheizagaiciuc,项目名称:n2cms,代码行数:7,代码来源:CommentRenderer.cs


示例16: SettingViewData_AlsoUpdatesViewBag

        public void SettingViewData_AlsoUpdatesViewBag()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            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(httpContext, 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"]);
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:26,代码来源:ViewContextTests.cs


示例17: PageForContext

 public string PageForContext(ViewContext context)
 {
     string name = Preferences.Get<string> (PrefKeyForContext (context));
     if (name == null)
         name = DefaultForContext (context);
     return name;
 }
开发者ID:iainlane,项目名称:f-spot,代码行数:7,代码来源:Sidebar.cs


示例18: CopyConstructor_CopiesExpectedProperties

        public void CopyConstructor_CopiesExpectedProperties()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var originalContext = new ViewContext(
                new ActionContext(httpContext, new RouteData(), new ActionDescriptor()),
                view: Mock.Of<IView>(),
                viewData: new ViewDataDictionary(metadataProvider: new EmptyModelMetadataProvider()),
                tempData: new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>()),
                writer: TextWriter.Null,
                htmlHelperOptions: new HtmlHelperOptions());
            var view = Mock.Of<IView>();
            var viewData = new ViewDataDictionary(originalContext.ViewData);
            var writer = new StringWriter();

            // Act
            var context = new ViewContext(originalContext, view, viewData, writer);

            // Assert
            Assert.Same(originalContext.ActionDescriptor, context.ActionDescriptor);
            Assert.Equal(originalContext.ClientValidationEnabled, context.ClientValidationEnabled);
            Assert.Same(originalContext.ExecutingFilePath, context.ExecutingFilePath);
            Assert.Same(originalContext.FormContext, context.FormContext);
            Assert.Equal(originalContext.Html5DateRenderingMode, context.Html5DateRenderingMode);
            Assert.Same(originalContext.HttpContext, context.HttpContext);
            Assert.Same(originalContext.ModelState, context.ModelState);
            Assert.Same(originalContext.RouteData, context.RouteData);
            Assert.Same(originalContext.TempData, context.TempData);
            Assert.Same(originalContext.ValidationMessageElement, context.ValidationMessageElement);
            Assert.Same(originalContext.ValidationSummaryMessageElement, context.ValidationSummaryMessageElement);

            Assert.Same(view, context.View);
            Assert.Same(viewData, context.ViewData);
            Assert.Same(writer, context.Writer);
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:35,代码来源:ViewContextTests.cs


示例19: RenderViewPage

		private void RenderViewPage(ViewContext context, 
			TextWriter writer, ViewPage page)
		{
			page.ViewData = context.ViewData;
			page.Output = writer;
			page.RenderView(context);
		}
开发者ID:radischevo,项目名称:Radischevo.Wahha,代码行数:7,代码来源:WebFormView.cs


示例20: RenderView

        private void RenderView(ScriptScope scope, ViewContext context, TextWriter writer)
        {
            scope.SetVariable("view_data", context.ViewData);
            scope.SetVariable("model", context.ViewData.Model);
            scope.SetVariable("context", context);
            scope.SetVariable("response", context.HttpContext.Response);
            scope.SetVariable("url", new RubyUrlHelper(context.RequestContext));
            scope.SetVariable("html", new RubyHtmlHelper(context, new Container(context.ViewData)));
            scope.SetVariable("ajax", new RubyAjaxHelper(context, new Container(context.ViewData)));

            var script = new StringBuilder();
            Template.ToScript("render_page", script);

            if (_master != null)
                _master.Template.ToScript("render_layout", script);
            else
                script.AppendLine("def render_layout; yield; end");

            script.AppendLine("def view_data.method_missing(methodname); get_Item(methodname.to_s); end");
            script.AppendLine("render_layout { |content| render_page }");

            try
            {
                _rubyEngine.ExecuteScript(script.ToString(), scope);
            }
            catch (Exception e)
            {
                writer.Write(e.ToString());
            }
        }
开发者ID:jdhardy,项目名称:ironrubymvc,代码行数:30,代码来源:RubyView.cs



注:本文中的ViewContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ViewDataDictionary类代码示例发布时间:2022-05-24
下一篇:
C# ViewBase类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap