Using MVC, look at this example where we have the following HTML code:
<p>Duma</p><img url='..' /><p>Duma</p>
I would like that print only the content of the tags, as: Duma Duma, removing the image, tags and showing only the text (as innerText)
I tried using Html.Raw() but it's not worked. Also I was reading about the class TabBuilder and creating a Html extension method, but I don't have idea about how to implemeted in my razor view.
You could make a string extension to strip the Html tags.
public static class StringExtensions
{
public static string StripHtml (this string inputString)
{
return Regex.Replace
(inputString, "<.*?>", string.Empty);
}
}
Then use it in your view
#myHtmlString.StripHtml()
You might need to declaring a using statement for the StringExtensions class or add it to the Web.Config file in your Views folder
#using My.Extensions.Namespace
OR
<system.web>
<pages>
<namespaces>
<add namespace="My.Extensions.Namespace" />
</namespaces>
</pages>
</system.web>
You could also make a Html Helper Extension
public static class HtmlExtensions
{
public static string StripHtml (this System.Web.Mvc.HtmlHelper helper, string htmlString)
{
return Regex.Replace
(htmlString, "<.*?>", string.Empty);
}
}
You can use this in your view like this
#Html.StripHtml(myHtmlString)
You will still need to add a reference to the namespace for your extension methods like above. Either adding to your Web.Config in your Views folder or adding a using statement in your view. The differences here is that adding it to your Web.Config file you will be able to use this extension method in all your views without adding the using statement.
Related
I am trying to implement this sample and for the life of me cannot get it to work:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring?view=aspnetcore-2.2#condition-tag-helper
What am I doing wrong
I have copied the code almost directly from the sample, only changing the namespace...
ConditionTagHelper.cs
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace My.TagHelpers
{
[HtmlTargetElement(Attributes = nameof(Condition))]
public class ConditionTagHelper : TagHelper
{
public bool Condition { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!Condition)
output.SuppressOutput();
}
}
}
_ViewImports.cshtml
#using My.TagHelpers
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper My.TagHelpers.ConditionTagHelper, My.TagHelpers
_Layout.cshtml is used, and is standard from the asp.net core MVC project
Home Controller just returns a View and the view contains only this.
Index.cshtml
<div condition="#true">Shown</div>
<div condition="#false">Hidden</div>
I expected only the word "Shown" to be on the screen, however both words appear.
Your _ViewImports.cshtml file is incorrect. You are not actually importing the taghelper into your project so it is not being evaluated. The parameters to #addTagHelper are
The full name of the TagHelper to add (including the namespace) or * for all
The name of the Assembly the TagHelper is in
So, assuming your assembly is called My, you need to change your line to
#addTagHelper My.TagHelpers.ConditionTagHelper, My
More information can be found in the official docs
I'm new to the world of WP7 and .net programming for that matter and i need help. I have a custom component that has a property that uses template binding.
<TextBlock Text="{TemplateBinding Info}" FontSize="20" Grid.Row="1" TextWrapping="{TemplateBinding TextWrap}"/>
I defined the dependency properties in the .cs file.
Now in my page.xaml i placed the custom component like so,
<rounded:RoundedImageView x:Name="pivotItem1" Info="Test bind" BorderBrush="White" ImageSrc="Images/default_service.png" TextWrap="Wrap"/>
Which works ok, now I want the Info and TextWrap properties to be changed dynamically based on some external variables so I did this
<rounded:RoundedImageView x:Name="pivotItem1" Info="{Binding sopInfo}" BorderBrush="White" ImageSrc="Images/default_service.png" TextWrap="{Binding wrap}"/>
where sopInfo and wrap are the external variables defined in the backing cs file of the page. But this doesn't work, the Info and TextWrap values do not change. How can i achieve it?
Thanks
Try to set the DataContext of your Page like this:
<phone:PhoneApplicationPage
DataContext="{Binding RelativeSource={RelativeSource Self}}" />
Then make sure that sopInfo and wrap are public DependancyProperties of your Page class.
public static readonly DependencyProperty sopInfoProperty =
DependencyProperty.Register(
"sopInfo", typeof(String),
);
public string sopInfo
{
get { return (string)GetValue(sopInfoProperty); }
set { SetValue(sopInfoProperty, value); }
}
I'd like to do something like
outputIdentity.Claims.Add(new Claim("Claim1", "<test>Hi</test>"))
However the security node within the response header itself shows it as
<Attribute Name="Claim1"><AttributeValue><test>Hi</test></AttributeValue></Attribute>
I know they are reserved XML characters getting translated but can't I specify that I want that node structure in my attribute?
NOTE: I've also tried wrapping it in CDATA however it serializes that tag too. When I replace the translated characters, it works.
Serialization of security tokens is done by the SecurityTokenHandler (in your case probably the Saml11SecurityTokenHandler).
If you want to customize serialization you have to overwrite the default behaviour by extending the Saml11SecurityTokenHandler class:
class CustomHandler : Saml11SecurityTokenHandler
{
public Saml11SecurityTokenHandler()
: base()
{
}
public Saml11SecurityTokenHandler(SamlSecurityTokenRequirement samlSecurityTokenRequirement)
: base(samlSecurityTokenRequirement)
{
}
public Saml11SecurityTokenHandler(XmlNodeList customConfigElements)
: base(customConfigElements)
{
}
protected override void WriteAttribute(XmlWriter writer, SamlAttribute attribute)
{
// your code here
}
}
You also have to add your custom security token handler in the web.config file:
<securityTokenHandlers>
<add type="Your.Namespace.CustomHandler, Your.Dll.Name, Version=1.0.0.0, Culture=neutral" />
</securityTokenHandlers>
EDIT: removed <clear />
Can you try wrapping the value in CDATA section? As:
<![CDATA[<test>Hi</test>]]> Not sure whether your SecurityTokenHandler class will handle that properly, but it's worth a try, and easier than introducing custom handlers.
I am using the latest version of MVCContrib and attempting to include a stylesheet via the following helper method:
<%=Html.Stylesheet(Links.Content.Site_css)%>
The path rendered is incorrectly calculated as:
<link type="text/css" rel="stylesheet" href="/content/css/Content/Site.css" />
The actual path should be: /Content/Site.css
Is this a bug?
The following methods work correctly:
METHOD 1: <%=Html.Stylesheet("~/Content/Site.css")%>
METHOD 2: <link type="text/css" rel="stylesheet" href="<%:Links.Content.Site_css %>" />
UPDATE 1:
Links.Content.Site_css represents a static field that is auto-generated using T4MVC
UPDATE 2:
Here is what the code generated by T4MVC looks like...
namespace Links {
...snipped for brevity...
[GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
public static class Content {
private const string URLPATH = "~/Content";
public static string Url() { return T4MVCHelpers.ProcessVirtualPath(URLPATH); }
public static string Url(string fileName) { return T4MVCHelpers.ProcessVirtualPath(URLPATH + "/" + fileName); }
public static readonly string Site_css = Url("Site.css");
}
Not a bug. This works as expected. Refer to Using MvcContrib ScriptInclude, Stylesheet, And T4MVC
the output of the T4MVC Links are relative paths that have been resolved (meaning they no longer have the “~”). The MVC Contrib Helpers assume that if the URL passed it it doesn’t have the “~”, then it will prepend either “~/Scripts/” for scripts or “~/content/css/'” for styles.
Seeing that I have moved my scripts, styles, and images under the “~/Content” folder, there are a couple of changes to the MVC Contrib Html Helpers that could make this work…
Provide some sort of mechanism to define the paths prepended to the Scripts and Styles if there is no “~”
Override the Html Helpers with another option to not prepend any path information
Possibly search for the “/” instead of the “~” when determining if a path should be prepended to the URL
I have a class like this:
public class RxNormFolderMgr
{
// properties
public string RxNormFolder { get { return ConfigurationSettings.AppSettings["rootFolder"].ToString(); } }
}
When I try to use it like this:
public class TestRxNormFolderManager : ColumnFixture
{
public string RxNormFolder()
{
RxNormFolderMgr folderMgr = new RxNormFolderMgr();
return folderMgr.RxNormFolder;
}
}
I get an error: "System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object." The AllKeys property for AppSettings is an array of zero length where I am expecting length of 1.
My app.config file in the project looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="rootFolder" value ="C:\RxNorm" />
<!-- Root folder must not end with slash. -->
</appSettings>
</configuration>
I know ConfigurationSettings.AppSettings is supposed to be obsolete and I should use ConfigurationManager.AppSettings, but I can't even get that to compile. I do have a reference in the project to System.configuration (c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll on my machine) and using statement at top of my code.
I am using Fitnesse to test the code, and that's when I get the error. It's my understanding that I should also place a copy of the app.config file in the Bin>Debug folder of the test fixtures project which I have done. So, I don't know why I'm getting this error still.
Please, help.
Also: try using the ConfigurationManager class instead of "ConfigurationSettings":
Use a check for NOT NULL first:
public class RxNormFolderMgr
{
// properties
public string RxNormFolder
{
get
{
if(ConfigurationManager.AppSettings["rootFolder"] != null)
{
return ConfigurationManager.AppSettings["rootFolder"].ToString();
}
return string.Empty;
}
}
}
Is this inside a class library assembly? Those never use their own app.config - but instead the use the host app's app.config (the app that uses the class library).
Marc
When you are testing with FitNesse, the actual executable running is "FitServer.exe" so AppSettings is looking for a "FitServer.exe.config" in the directory with FitServer.exe lives. So a quick and dirty solution is to copy your app.config there and rename it.
A better solution is to specify the app config as described here:
http://www.syterra.com/FitnesseDotNet/ApplicationConfigurationFile.html
or if you're using fitSharp (which is an enhancement of FitNesse.NET):
http://www.syterra.com/Fit/AppConfigFiles.html
Do not put it in appsettings. Use <connectionStrings>
example:
<appSettings/>
<connectionStrings>
<add name="NORTHWNDConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
string cnstr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ToString();