Html.LabelFor not rendering HTML - asp.net-mvc-4

I am binding a model to view.
public class Validation
{
[Display("Please enter in <h5>day(s)</h5>")]
public string Message { get; set; }
}
Here Message property will be set as Please enter in <h5>day(s)</h5>.
In view am binding model property to LabelFor.
#Html.LabelFor(m => m.Message)
Expecting output as
Please enter in day(s)
But actual output is
Please enter in <h5>day(s)</h5>
I want part of the string to vary in size and cosmetics, so applying CSS to the entire label is not what I'm looking for.

Your display string "<h5>some text</h5>" will be rendered as text, not HTML. MVC will encode the < > characters to < >, causing them to be displayed as-is.
You shouldn't want to do this like this anyway.
The proper way would be to apply the display string to contain the text you want:
[Display("some text")]
Then create a CSS class:
label.fancyLabel {
/* your style here that makes a label look like a h5 */
}
Then apply that class to the label (from .NET MVC - How to assign a class to Html.LabelFor?):
#Html.LabelFor(m => m.Message, new { #class= "fancyLabel" })
As for your edit, if you want to just render the Display attribute's text as literal HTML, you'll have to:
Introduce your own HTML helper.
In there, write a label (and make sure to set the for= attribute).
Read the DisplayAttribute's value.
#Html.Raw() that value as the label text.
Use #Html.YourLabelHelper(m => m.Message) to render it.
But using HTML on your models like that isn't really advisable. Views and templates should decide how to render a model, not the other way around.

Related

CKEditor 5 copy selected content from one editor to another

I have two editors on the screen, one read-only. What I want to do is allow the user to select content from the read-only editor and paste it into the current position of the other by clicking a button. (the logic may manipulate the text which is one reason I don't want to use the system's clipboard.)
So far I have the function that is able to paste the text like as follows. (I am using the Angular wrapper which explains the presence of the CKEditorComponent reference.
doPaste(pasteEvent: PasteEvent, editorComponent: CKEditorComponent) {
const editor = editorComponent.editorInstance;
editor.model.change(writer => {
writer.insertText(pasteEvent.text, editor.model.document.selection.getFirstPosition() );
});
}
What I can't find from the documentation is how to extract the selected text. What I have so far is:
clickPasteSelectedPlain(editorComponent: CKEditorComponent) {
const editor = editorComponent.editorInstance;
const selection = editor.model.document.selection;
console.log('clickPasteAll selection', selection);
console.log('clickPasteAll selectedcontent', editor.model.document.getSelectedContent);
}
The selection appears to change depending on what is selected in the editor's view. The getSelectedContent function is undefined. How do I get the content?
With a bit of poking around I figured out how to do this. I'll document it here on the chance that it will help someone down the road avoid the process of discovery that I went through.
On the source document I have a ckeditor element like this:
<div *ngIf="document">
<ckeditor #ckEditor
[editor]="Editor" [config]="ckconfig" [disabled]="true"
[(ngModel)]="document.text"></ckeditor>
<button mat-flat-button (click)="clickPasteSelectedPlain(ckEditor)">Paste Selected Text Plain</button>
</div>
In the component the function called on the click event is like this:
#Output() paste = new EventEmitter<PasteEvent>();
...
clickPasteSelectedPlain(editorComponent: CKEditorComponent) {
const editor = editorComponent.editorInstance;
this.paste.emit({
content: editor.model.getSelectedContent(editor.model.document.selection),
obj: this.document,
quote: false
});
}
The PasteEvent is defined as an exported interface which I will omit here to save space. The content key will refer to a DocumentFragment.
Note that I am passing the CKEditorComponent as a parameter. You could also access it via an Angular #ViewChild declaration but note that my ckeditor is inside an *ngIf structure. I think that works well in Angular 6 but in the past I have had difficulty with #ViewChild references when the target was conditionally in the DOM. This method always works but use whatever method you want.
The event fired by the emit is processed with a method that looks like this:
doPaste(pasteEvent: PasteEvent, editorComponent: CKEditorComponent) {
const editor = editorComponent.editorInstance;
editor.model.insertContent(pasteEvent.content);
}
Because the content is a DocumentFragment the paste operation will include all formatting and text attributes contained in the selected source. But that's all there is to it.

FluentBootstrap - Acces to the form object from partial views

I have a view that renders a form with code similar to the following:
#using( var form = Bootstrap.Form().SetHorizontal( 3 ).AddCss( Css.ColSm8, Css.ColMdOffset2 ).Begin() )
{
#form.DisplayFor( m => m.Name )
// bla bla bla
#Html.Action( "Details", "Fare", new { entity = Model.FareId } )
}
How can I access the form object in the partial view, so that the same layout is applied to the whole form?
A lot of work was spent ensuring that the Bootstrap control stack would carry-over into partial views. You have two options here:
The first is to just pass the form object to the partial/action as part of the model. In your case, you would just add it as another property in the anonymous model object you're sending to the action.
You don't need to use the form instance to make FluentBootstrap recognize you're in a form. It's just a convenience to make calling the extensions appropriate to a form easier. You can also just call something like Bootstrap.DisplayFor(x => x.Name) right from the global Bootstrap object in your partial and it will respect any settings you've placed in the containing form defined in the containing view.

Sitecore MVC Custom Link

I am trying to create a custom link from sitecore into my view
#Html.Sitecore().Field("CTA display", Model.Item, new { text = "<span>" + + "</span>"})
I am not 100% sure what the correct way to do this is, but I want to wrap the text from the link into a for styling. I've tried to put the Model.Rendering.Item.Fields["CTA display"] into there with .Text and it doesn't work.
Any help would be appreciated.
First, I'd start by creating a SitecoreHelper extension method that allows you to modify the inner html of the element you're rendering:
public static HtmlString Field(this SitecoreHelper helper, string fieldName, Item item, object parameters, string innerHtml)
{
if (helper == null)
{
throw new ArgumentNullException("helper");
}
if (innerHtml.IsNullOrEmpty())
{
return helper.Field(fieldName, item, parameters);
}
return new HtmlString(helper.BeginField(fieldName, item, parameters).ToString() + innerHtml + helper.EndField().ToString());
}
This will allow you to pass an optional innerHtml string that will be inserted between opening and closing tags of your element (in this case, an <a> tag).
From here, pass your html string containing your CTA label to the above method, or modify the method to output the field's Text value wrapped in a <span>.
I used the solution posted above by computerjules which worked a treat. You can then called the extended method like follows
#Html.Sitecore().Field("Link", Html.Sitecore().CurrentItem, new {Class = "some-class"}, "<span class='some-other-class'></span>")
and the span is rendered within the anchor tabs

Using Rich Text Editor in Orchard CMS Custom Module

I am creating a custom module in Orchard CMS 1.7.1
So far all is going well (ish)
One of my properties is a string (called InfoBubbleHtml).
I would like to utilise the rich text edit for this input on my modules create/edit form.
Is there a helper already in place that would render my property as a rich text area rather than just a textarea or input field?
If not, what would i need to do to be able to have this property render the rich text editor?
Thanks in advance.
Update
As an update/addition to this question... Any HTML that I enter into my current text area is being ignored; guessing to do with request validation. how is this disabled for my controller so i can allow html in the admin?
Update 2
Ok, so i have figured out how to add this to my view by using:
#Display.Body_Editor(Text:Model.InfoBubbleHtml,EditorFlavor:"html")
Any idea how to set the ID of the editor?
#Display.Body_Editor(Text:Model.InfoBubbleHtml,EditorFlavor:"html") is rendering a shape named Body.Editor.cshtml.
This file lives in : Orchard.Web\Core\Common\Views\Body.Editor.cshtml
And it's content is
#using Orchard.Utility.Extensions;
#{
string editorFlavor = Model.EditorFlavor;
}
#Html.TextArea("Text", (string)Model.Text, 25, 80, new { #class = editorFlavor.HtmlClassify() })
So using this Shape you cannot set Id, Model is the anon that you send on the Display (Text and EditorFlavor).
Shapes.cs on Orchard.Core/Common is hooking an alternate using the EditoFlavor string.
public void Discover(ShapeTableBuilder builder) {
builder.Describe("Body_Editor")
.OnDisplaying(displaying => {
string flavor = displaying.Shape.EditorFlavor;
displaying.ShapeMetadata.Alternates.Add("Body_Editor__" + flavor);
});
}
So the final file that is rendered : TinyMVC\Views\Body-Html.Editor.cshtml
using Orchard.Environment.Descriptor.Models
#{
var shellDescriptor = WorkContext.Resolve<ShellDescriptor>();
}
<script type="text/javascript">
var mediaPickerEnabled = #(shellDescriptor.Features.Any(x => x.Name == "Orchard.MediaPicker") ? "true" : "false");
var mediaLibraryEnabled = #(shellDescriptor.Features.Any(x => x.Name == "Orchard.MediaLibrary") ? "true" : "false");
</script>
#{
Script.Require("OrchardTinyMce");
Script.Require("jQueryColorBox");
Style.Require("jQueryColorBox");
}
#Html.TextArea("Text", (string)Model.Text, 25, 80,
new Dictionary<string,object> {
{"class", "html tinymce"},
{"data-mediapicker-uploadpath",Model.AddMediaPath},
{"data-mediapicker-title",T("Insert/Update Media")},
{"style", "width:100%"}
})
You need to add this to the template and include another parameter in the TextArea Dictionary parameter named : {"id", "THE ID YOU LIKE"}.
Take a look at the docs about Shapes if you want to learn more Docs
You can patch the TinyMVC\Views\Body-Html.Editor.cshtml file to enable it to use custom Name/ID for the text area. The modification is quite simple - replace
#Html.TextArea("Text", (string)Model.Text, 25, 80,
with
#Html.TextArea((string)Model.PropertyName ?? "Text", (string)Model.Text, 25, 80,
Now you can use additional parameter PropertyName in your call:
#Display.Body_Editor(PropertyName:"InfoBubbleHtml", Text:Model.InfoBubbleHtml, EditorFlavor:"html")
The downside is that you are patching a foreign code and have to reapply this patch every time this file in TinyMVC module is updated.

Separate UIHints for display and edit in mvc4

Is it possible to have separate uihint templates, one for display and the other for edit? If yes, how to achieve this?
For ex:
public class PartyRole
{
[Required]
[UIHint("DropDownList")]
public int PartyRoleTypeId { get; set; }
}
I am using EditForModel() and DisplayForModel().
In edit, I am showing the property as drop down. But in display I should show it as simple text.
Is it possible to have separate uihint templates, one for display and the other for edit?
No, this is not possible. It should be the same name. The EditorTemplate is located in ~/Views/Shared/EditorTemplates and the display template in ~/Views/Shared/DisplayTemplates. If for some reason you absolutely needed to have different names for the templates you could pass them as parameter to the helpers instead of using UIHint:
#Html.EditorFor(x => x.Foo, "SomeEditorTemplate")
#Html.DisplayFor(x => x.Foo, "SomeDisplayTemplate")