本文整理汇总了C#中System.HtmlHelper类的典型用法代码示例。如果您正苦于以下问题:C# HtmlHelper类的具体用法?C# HtmlHelper怎么用?C# HtmlHelper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HtmlHelper类属于System命名空间,在下文中一共展示了HtmlHelper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: HiddenInput
public static string HiddenInput(HtmlHelper html)
{
if (html.Context.ViewData.Metadata.HideSurroundingChrome)
return System.String.Empty;
return String(html);
}
示例2: HiddenInputTemplate
internal static string HiddenInputTemplate(HtmlHelper html) {
string result;
if (html.ViewContext.ViewData.ModelMetadata.HideSurroundingChrome) {
result = String.Empty;
}
else {
result = DefaultDisplayTemplates.StringTemplate(html);
}
object model = html.ViewContext.ViewData.Model;
Binary modelAsBinary = model as Binary;
if (modelAsBinary != null) {
model = Convert.ToBase64String(modelAsBinary.ToArray());
}
else {
byte[] modelAsByteArray = model as byte[];
if (modelAsByteArray != null) {
model = Convert.ToBase64String(modelAsByteArray);
}
}
result += html.Hidden(String.Empty, model).ToHtmlString();
return result;
}
示例3: SetUp
public void SetUp()
{
string siteRoot = GetSiteRoot();
string viewPath = Path.Combine(siteRoot, "RenderingTests\\Views");
Layout = null;
PropertyBag = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
Helpers = new HelperDictionary();
StubMonoRailServices services = new StubMonoRailServices();
services.UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), new StubRoutingEngine());
services.UrlTokenizer = new DefaultUrlTokenizer();
UrlInfo urlInfo = new UrlInfo(
"example.org", "test", "/TestBrail", "http", 80,
"http://test.example.org/test_area/test_controller/test_action.tdd",
Area, ControllerName, Action, "tdd", "no.idea");
StubEngineContext = new StubEngineContext(new StubRequest(), new StubResponse(), services,
urlInfo);
StubEngineContext.AddService<IUrlBuilder>(services.UrlBuilder);
StubEngineContext.AddService<IUrlTokenizer>(services.UrlTokenizer);
StubEngineContext.AddService<IViewComponentFactory>(ViewComponentFactory);
StubEngineContext.AddService<ILoggerFactory>(new ConsoleFactory());
StubEngineContext.AddService<IViewSourceLoader>(new FileAssemblyViewSourceLoader(viewPath));
ViewComponentFactory = new DefaultViewComponentFactory();
ViewComponentFactory.Service(StubEngineContext);
ViewComponentFactory.Initialize();
ControllerContext = new ControllerContext();
ControllerContext.Helpers = Helpers;
ControllerContext.PropertyBag = PropertyBag;
StubEngineContext.CurrentControllerContext = ControllerContext;
Helpers["urlhelper"] = Helpers["url"] = new UrlHelper(StubEngineContext);
Helpers["htmlhelper"] = Helpers["html"] = new HtmlHelper(StubEngineContext);
Helpers["dicthelper"] = Helpers["dict"] = new DictHelper(StubEngineContext);
Helpers["DateFormatHelper"] = Helpers["DateFormat"] = new DateFormatHelper(StubEngineContext);
//FileAssemblyViewSourceLoader loader = new FileAssemblyViewSourceLoader(viewPath);
// loader.AddAssemblySource(
// new AssemblySourceInfo(Assembly.GetExecutingAssembly().FullName,
// "Castle.MonoRail.Views.Brail.Tests.ResourcedViews"));
viewEngine = new AspViewEngine();
viewEngine.Service(StubEngineContext);
AspViewEngineOptions options = new AspViewEngineOptions();
options.CompilerOptions.AutoRecompilation = true;
options.CompilerOptions.KeepTemporarySourceFiles = false;
ICompilationContext context =
new CompilationContext(
new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory),
new DirectoryInfo(siteRoot),
new DirectoryInfo(Path.Combine(siteRoot, "RenderingTests\\Views")),
new DirectoryInfo(siteRoot));
List<ICompilationContext> compilationContexts = new List<ICompilationContext>();
compilationContexts.Add(context);
viewEngine.Initialize(compilationContexts, options);
}
示例4: ObjectTemplate
internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {
ViewDataDictionary viewData = html.ViewContext.ViewData;
TemplateInfo templateInfo = viewData.TemplateInfo;
ModelMetadata modelMetadata = viewData.ModelMetadata;
StringBuilder builder = new StringBuilder();
if (templateInfo.TemplateDepth > 1) { // DDB #224751
return modelMetadata.Model == null ? modelMetadata.NullDisplayText : modelMetadata.SimpleDisplayText;
}
foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => pm.ShowForEdit && !templateInfo.Visited(pm))) {
if (!propertyMetadata.HideSurroundingChrome) {
string label = LabelExtensions.LabelHelper(html, propertyMetadata, propertyMetadata.PropertyName).ToHtmlString();
if (!String.IsNullOrEmpty(label)) {
builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"editor-label\">{0}</div>\r\n", label);
}
builder.Append("<div class=\"editor-field\">");
}
builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.Edit));
if (!propertyMetadata.HideSurroundingChrome) {
builder.Append(" ");
builder.Append(html.ValidationMessage(propertyMetadata.PropertyName, "*"));
builder.Append("</div>\r\n");
}
}
return builder.ToString();
}
示例5: ObjectTemplate
internal static string ObjectTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper) {
ViewDataDictionary viewData = html.ViewContext.ViewData;
TemplateInfo templateInfo = viewData.TemplateInfo;
ModelMetadata modelMetadata = viewData.ModelMetadata;
StringBuilder builder = new StringBuilder();
if (modelMetadata.Model == null) { // DDB #225237
return modelMetadata.NullDisplayText;
}
if (templateInfo.TemplateDepth > 1) { // DDB #224751
return modelMetadata.SimpleDisplayText;
}
foreach (ModelMetadata propertyMetadata in modelMetadata.Properties.Where(pm => pm.ShowForDisplay && !templateInfo.Visited(pm))) {
if (!propertyMetadata.HideSurroundingChrome) {
string label = propertyMetadata.GetDisplayName();
if (!String.IsNullOrEmpty(label)) {
builder.AppendFormat(CultureInfo.InvariantCulture, "<div class=\"display-label\">{0}</div>", label);
builder.AppendLine();
}
builder.Append("<div class=\"display-field\">");
}
builder.Append(templateHelper(html, propertyMetadata, propertyMetadata.PropertyName, null /* templateName */, DataBoundControlMode.ReadOnly));
if (!propertyMetadata.HideSurroundingChrome) {
builder.AppendLine("</div>");
}
}
return builder.ToString();
}
示例6: Decimal
public static string Decimal(HtmlHelper html)
{
if (html.Context.ViewData.Template.Value == html.Context.ViewData.Model)
html.Context.ViewData.Template.Value = string.Format(CultureInfo.CurrentCulture,
"{0:0.00}", html.Context.ViewData.Model);
return String(html);
}
示例7: Test1
public void Test1()
{
//string content = DownloadHelper.Download("");
//DownloadHelper.ParseIndexPage("http://yongche.16888.com/index.html");
//DownloadHelper download = new DownloadHelper();
//download.DownloadFromRequest("http://yongche.16888.com/index.html");
//string targetPath = "c:\\a.html";
//1. write website rule
//2. save website info or send it to MQ queue
/*List<UrlModel> urls = new List<UrlModel>(){
UrlManager.CreateModel("http://yongche.16888.com/mrzs/index_1_1.html","美容知识"),
UrlManager.CreateModel("http://yongche.16888.com/yfzs/index_1_1.html","养护知识"),
UrlManager.CreateModel("http://yongche.16888.com/gzzs/index_1_1.html","改装知识"),
UrlManager.CreateModel("http://yongche.16888.com/cjzs/index_1_1.html","车居知识"),
UrlManager.CreateModel("http://yongche.16888.com/cyp/index_1_1.html","汽车用品"),
UrlManager.CreateModel("http://yongche.16888.com/bszh/index_1_1.html","保险知识"),
UrlManager.CreateModel("http://yongche.16888.com/wxzs/index_1_1.html","维修知识")
};
RuleModel rule = RuleManager.CreateModel("//dt[1]//a[2]", "//div[@class='news_list']//dl",
"//dt[1]//a[@class='f_gray']", "//dt[1]//span[@class='ico_j']",
"//dd[1]//span[1]", "//dd[1]//img[1]", "//dt[1]//span[@class='f_r']");
WebSiteModel model = WebSiteManager.CreateModel(urls, rule, "addr");*/
WebSiteModel model = CreateTestModel();
string result = JsonHelper.Serializer(model);
FileHelper.WriteTo(result, "c:\\bb.data");
//2. download from url
//3. save result
WebSiteModel newModel = WebSiteManager.GetSiteInfo("c:\\bb.data");
HtmlHelper helper = new HtmlHelper();
List<string> targetPaths = new List<string>();
foreach (UrlModel item in newModel.DownloadUrls)
{
string url = item.Url;
string localDriver = "c:\\";
string targetPath = string.Format("{0}{1}.html", localDriver, FileHelper.GenerateFileName(url));
helper.Download(url);
helper.SaveTo(helper.M_Html, targetPath);
targetPaths.Add(targetPath);
}
//4. pase page from local file
WebSiteModel parseModel = WebSiteManager.GetSiteInfo("c:\\bb.data");
YongcheHtmlHelper yongche = new YongcheHtmlHelper();
string tempContent = System.IO.File.ReadAllText(targetPaths[0], Encoding.Default);
List<Article> articles = yongche.ParseArticle(tempContent, parseModel);
}
示例8: BooleanTemplate
internal static string BooleanTemplate(HtmlHelper html) {
bool? value = null;
if (html.ViewContext.ViewData.Model != null) {
value = Convert.ToBoolean(html.ViewContext.ViewData.Model, CultureInfo.InvariantCulture);
}
return html.ViewContext.ViewData.ModelMetadata.IsNullableValueType
? BooleanTemplateDropDownList(html, value)
: BooleanTemplateCheckbox(html, value ?? false);
}
示例9: RouteLinkHtmlElement
/// <summary>
/// Initializes a new instance of the <see cref="RouteLinkHtmlElement"/> class.
/// </summary>
/// <param name="routeName">The name of the target route.</param>
/// <param name="htmlHelper">The helper used to render HTML.</param>
public RouteLinkHtmlElement(string routeName, HtmlHelper htmlHelper)
: base(htmlHelper)
{
if (routeName.IsNullOrEmpty())
{
throw new ArgumentException("Route name cannot be null or empty.", "routeName");
}
this.routeName = routeName;
}
示例10: DefaultRouteCollectionIsRouteTableRoutes
public void DefaultRouteCollectionIsRouteTableRoutes() {
// Arrange
var viewContext = new Mock<ViewContext>().Object;
var viewDataContainer = new Mock<IViewDataContainer>().Object;
// Act
var htmlHelper = new HtmlHelper(viewContext, viewDataContainer);
// Assert
Assert.AreEqual(RouteTable.Routes, htmlHelper.RouteCollection);
}
示例11: ViewContextProperty
public void ViewContextProperty() {
// Arrange
ViewContext viewContext = new Mock<ViewContext>().Object;
HtmlHelper htmlHelper = new HtmlHelper(viewContext, new Mock<IViewDataContainer>().Object);
// Act
ViewContext value = htmlHelper.ViewContext;
// Assert
Assert.AreEqual(viewContext, value);
}
示例12: ViewDataContainerProperty
public void ViewDataContainerProperty() {
// Arrange
ViewContext viewContext = new Mock<ViewContext>().Object;
IViewDataContainer container = new Mock<IViewDataContainer>().Object;
HtmlHelper htmlHelper = new HtmlHelper(viewContext, container);
// Act
IViewDataContainer value = htmlHelper.ViewDataContainer;
// Assert
Assert.AreEqual(container, value);
}
示例13: GetDetailHtml
public override void GetDetailHtml(Product product, Site site)
{
loginfo.Location = this.GetType().Name + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
loginfo.Url = product.Url;
loginfo.KeyInfo = site.SiteName;
HtmlHelper html = new HtmlHelper(product.Html);
//get product detail nodes
var product_node = html.GetNodeByXPath("//div[@class='products']/div[@class='product']/div[@class='desktop']");
//get product description
var description_nodes = html.GetNodesByXPath("./div[@class='bottom']/div[1]/div[1]/div[@class='description open-sans-regular']/*",product_node);
string description = "";
if (description_nodes.Count > 0)
{
foreach (var sellpoint_node in description_nodes)
{
if (sellpoint_node.Equals(description_nodes.First()))
{
description += sellpoint_node.FirstChild.InnerText.Trim();
}
else
{
description += "|" + sellpoint_node.FirstChild.InnerText.Trim();
}
}
}
//get sell point
var sellpoint_nodes = html.GetNodesByXPath("./div[@class='bottom']/div[1]/div[1]/div[@class='bullets open-sans-regular']/div", product_node);
string sellpoints = "";
if(sellpoint_nodes.Count>0)
{
foreach(var sellpoint_node in sellpoint_nodes)
{
if (sellpoint_node.Equals(sellpoint_nodes.First()))
{
sellpoints += sellpoint_node.FirstChild.InnerText.Trim();
}
else
{
sellpoints += "|" + sellpoint_node.FirstChild.InnerText.Trim();
}
}
}
product.Description = description;
product.SellPoint = sellpoints;
}
示例14: CollectionTemplate
internal static string CollectionTemplate(HtmlHelper html, TemplateHelpers.TemplateHelperDelegate templateHelper)
{
object model = html.ViewContext.ViewData.ModelMetadata.Model;
if (model == null) {
return String.Empty;
}
IEnumerable collection = model as IEnumerable;
if (collection == null) {
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
MvcResources.Templates_TypeMustImplementIEnumerable,
model.GetType().FullName
)
);
}
Type typeInCollection = typeof(string);
Type genericEnumerableType = TypeHelpers.ExtractGenericInterface(collection.GetType(), typeof(IEnumerable<>));
if (genericEnumerableType != null) {
typeInCollection = genericEnumerableType.GetGenericArguments()[0];
}
bool typeInCollectionIsNullableValueType = TypeHelpers.IsNullableValueType(typeInCollection);
string oldPrefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix;
try {
html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = String.Empty;
string fieldNameBase = oldPrefix;
StringBuilder result = new StringBuilder();
int index = 0;
foreach (object item in collection) {
Type itemType = typeInCollection;
if (item != null && !typeInCollectionIsNullableValueType) {
itemType = item.GetType();
}
ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() => item, itemType);
string fieldName = String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", fieldNameBase, index++);
string output = templateHelper(html, metadata, fieldName, null /* templateName */, DataBoundControlMode.Edit, null /* additionalViewData */);
result.Append(output);
}
return result.ToString();
}
finally {
html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;
}
}
示例15: Render
/// <summary>
/// Renders a script block to the specified
/// <paramref name="writer"/>.
/// </summary>
/// <param name="writer">A <see cref="System.IO.TextWriter"/>
/// to render the script block to.</param>
internal void Render(TextWriter writer)
{
HtmlHelper helper = new HtmlHelper(_manager._context);
StringBuilder builder = new StringBuilder(Environment.NewLine);
foreach (string code in _scripts.Where(a => a != null)
.Select(a => helper.Block(a)))
builder.AppendLine(code);
if (builder.Length > Environment.NewLine.Length)
writer.WriteLine((_wrapper == null) ?
builder.ToString() :
helper.Block(_wrapper, builder.ToString()));
}