Inline Razor output after dash - asp.net-mvc

I don't know how to output a variable in Razor as part of an attribute name after a dash:
<span data-#(DataAttributeName)="value"/>
// fails, output:
<span data-#(DataAttributeName)="value"/>
<span data- #(DataAttributeName)="value"/>
// works, however, the space results in invalid HTML:
<span data- myname="value"/>
How to do that properly?
Currently, I have the following workaround:
<span #("data-" + DataAttributeName)="value"/>
But I don't like it for obvious style reasons + Visual Studio tells me that "an attribute name is expected" and shows an error (although it seems to work properly), also something I don't like.

That's a tricky part in razor engine, it tries to be smart to save some escape but sometimes leave no easy solution in scenarios like this.
Just to stay neat, I may create a HtmlHelper Extension, which might be a overkill, but just in case you are sick of red things in editor like me :)
public static class MyHtmlHelperExtension
{
public static MvcHtmlString DataAttribute(this HtmlHelper helper, string attrName, string value)
{
return new MvcHtmlString(string.Format("data-{0}='{1}'", attrName, value));
}
}
Then in your view it can be somehow cleaner:
<span #Html.DataAttribute(DataAttributeName, "value") />

Related

Checkboxes generated via CheckBoxFor helper turn into type=hidden because of MaterializeCSS

I'm creating a website with ASP.NET MVC5 and I'm using MaterializeCSS for the first time, which looks like a very exciting framework.
However, the checkboxes generated by CheckBoxFor helper become hidden !
When I write :
#Html.CheckBoxFor(m => m.IsAgreeTerms)
The generated HTML is :
<input name="IsAgreeTerms" type="hidden" value="false">
Why does Materialize change my type=checkbox into type=hidden ?
I tried to add type="checkbox" in the CheckboxFor helper, but it doesnt change anything. The only way is to modify in in my browser's console.
The only solution I found is this SO thread.
However, the accepted answer doesn't change anything for me.
The other answer works, but I think it's ugly to add some JS script to modify what Materialize modifies without my consent.
Is there any way to say "Hey, I ask for a type=checkbox, so just let my type=checkbox in the generated HTML" ?
Thank you
UPDATE :
My full ASP.NET MVC code is :
#Html.CheckBoxFor(m => m.IsAgreeTerms, new { #type = "checkbox" })
#Html.LabelFor(m => m.IsAgreeTerms, new { #class = "login-label" })
The full generated HTML is
<input data-val="true" data-val-required="Le champ IsAgreeTerms est requis." id="IsAgreeTerms" name="IsAgreeTerms" type="checkbox" value="true"
<input name="IsAgreeTerms" type="hidden" value="false">
<label class="login-label" for="IsAgreeTerms">IsAgreeTerms</label>
Here's a solution in the form of a html helper. It constructs a checkbox and label in the correct order:
public static IHtmlString CheckBoxWithLabelFor<TModel>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, bool>> expression,
string labelText,
object htmlAttributes = null
)
{
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
var checkBoxWithHidden = htmlHelper.CheckBoxFor(expression, htmlAttributes).ToHtmlString().Trim();
var pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1, StringComparison.Ordinal));
var labelHtml = htmlHelper.LabelFor(expression, labelText).ToHtmlString().Trim();
var result = pureCheckBox + Environment.NewLine + labelHtml + Environment.NewLine + $"<input type=\"hidden\" name=\"{ExpressionHelper.GetExpressionText(expression)}\" value=\"false\" />";
return new MvcHtmlString(result);
}
Is there other html generated by materialize.css? I think this happens because it is not possible apply a custom CSS to element input of type checkbox.
So, the checkbox becomes hidden and other html component represents visually the checkbox. Many components work like that.
UPDATE:
Why is Html checkbox generating an additional hidden input
OP here. Problem looks like more complex.
Actually, when using #Html.CheckBoxFor, MVC5 generates 3 fields, in that order :
Your input, with type="checkbox", binded to your model property
An hidden field (see the Claudio's link for an explaination)
Your label, generated by #Html.LabelFor
Problem is Materialize expects that in another order to work.
In your browser's console, just move the <label> element between the input and the hidden field, and everything works fine !
I found this very useful link, where, basically, it is said that the order of the generated fields by #Html.checkBoxFor will change ... In MVC6 !
As I'm working with MVC5, I use this very ugly solution in my _Layout:
$(":checkbox").each(function () {
$(this).nextAll("label").before($(this))
})
If anyone has a better idea, please feel free to post an elegant solution.

Html.TextArea generates extra line break by default

I'm rendering a usual textarea like this:
#Html.TextAreaFor(x => x.Description)
I expected to see an empty textarea but here is what I see instead (I selected the first line to make it more clear):
I checked out the generated html and it contains a line break between an opening and closing tags:
<textarea class="form-control" cols="20" id="Description" name="Description" rows="2">
</textarea>
Is that done by design? Can I change this behaviour?
After saw your question, I research on Google to see what is the issue behind extra line in #Html.TextAreaFor. Have a look.
There are some articles those are related to your issue:-
http://www.peschuster.de/2011/11/new-line-bug-in-asp-net-mvcs-textarea-helper/
ASP.NET MVC Textarea HTML helper adding lines when using AntiXssLibrary
Articles suggested that basic issue in TextAreaHelper class which is used by #Html.TextAreaFor.
private static MvcHtmlString TextAreaHelper(HtmlHelper htmlHelper,
ModelMetadata modelMetadata, string name, IDictionary<string,
object> rowsAndColumns, IDictionary<string, object> htmlAttributes)
{
// Some initialization here...
TagBuilder tagBuilder = new TagBuilder("textarea");
// Some more logic...
tagBuilder.SetInnerText(Environment.NewLine + attemptedValue);
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}
and the issue in above code is
tagBuilder.SetInnerText(Environment.NewLine + attemptedValue);
That's why actual output of #Html.TextAreaFor will be like this and extra line shows up:-
<textarea>
This is the content...</textarea>
The workaround of this problem is to
1st Workaround Implementing a Javascript onLoad fix to remove the offending encoding from all textareas:
$("textarea").each(function () { $(this).val($(this).val().trim()); });
2nd Workaround create your own helper for rendering textarea markup in views
public static MvcHtmlString FixedTextAreaFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return new MvcHtmlString(htmlHelper.TextAreaFor(expression)
.ToHtmlString()
.Replace(">
", ">" + Environment.NewLine));
}
These articles also suggested that this problem will be fixed in MVC 4 Developer Preview!

Dynamically bind (or format) two #observable variables to a third #observable variable

Here's something I thought might be a bit easier. Despite the specifics of the question, I'm interested in any method that will let me have a third form field auto-updated based on the content of two other fields with Polymer.dart.
Something like this, where the "[ ]" represent form fields.
Name: [given name] [family name]
Full name: [family_name, given_name]
So for example; if someone enters "John" and "Smith" in the first two fields. Then the "full name" line shows: [Smith, John], when either of the fields are updated.
I've based the following example on the classes and mark-up from the form Dart Polymer tutorial
Get Input from a Form tutorial
For a form like this ...
<polymer-element name="reference-form" extends="form" >
<template>
<style> ... </style>
<div id="slambookform" >
<div class="entry">
<label>Author:</label>
<input type="text" value="{{theData['authorGivenName']}}" >
<input type="text" value="{{theData['authorFamilyName']}}">
</div>
:
<div class="entry">
<label>Full name:</label>
<input disabled type="text" value="{{fullName}}" >
</div>
:
</div>
<template>
</polymer-element>
My initial attempt to make this happen was a function like:
#observable
String fullName(){
return theData['authorFamilyName'] +', '+ theData['authorGivenName'];
}
Which doesn't work. When I make 'fullName' to an #observable variable and update it with a button the form is updates as required. Hence my question, can I bind a third field to two (or more) others?
I think I will need some kind of event handler. For two fields, formatting on a change even is simple enough. I want to format several fields in the ultimate case, not just two fields.
While on this topic, is there a hook in dart-polymer or dart to supply a future or call-back? In my example, something like: 'after-change'. Just thinking out loud, something like that would be good.
Thanks in advance.
Along those lines (caution - code is not tested)
<polymer-element name="reference-form" extends="form" >
<template>
<style> ... </style>
<div id="slambookform" >
<div class="entry">
<label>Author:</label>
<input type="text" value="{{authorGivenName}}" >
<input type="text" value="{{authorFamilyName}}">
</div>
:
<div class="entry">
<label>Full name:</label>
<input disabled type="text" value="{{fullName}}" >
</div>
:
</div>
<template>
</polymer-element>
class reference_form.dart
String _authorGivenName;
#observable get authorGivenName => _authorGivenName;
set authorGivenName(String val) {
_authorGivenName = val;
notifyPropertyChange(#fullName, '${_authorGivenName} ${_authorFamilyName}',
'${val} ${_authorFamilyName}');
}
String _authorFamilyName;
#observable get authorFamilyName => _authorFamilyName;
set authorFamilyName(String val) {
_authorFamilyName = val;
notifyPropertyChange(#fullName, '${_authorGivenName} ${_authorFamilyName}',
'${_autorGivenName} ${val}');
}
#observable
String get fullName => '${_authorGivenName} ${_authorFamilyName}';
I have a workaround for this problem, standing on the shoulders of Günter Zöchbauer (comment above). My objective is to "bind" one field value to two in a read-only fashion. We are not quite there yet, however the pathway is educational in its own right.
Observer method
This solution is kind of a workaround for the objective I set myself. I've made some annotations on this code to explain what I saw, or why I think is happening.
The intention is for fullName to show both names in the form:
familyName, givenName; e.g.
Smith, John
reference-form.html:
<polymer-element name="reference-form" extends="form" >
<template>
<style> ... </style>
<div id="slambookform" >
<div class="entry">
<label>Author:</label>
<input type="text" value="{{theData['givenName']}}" >
<input type="text" value="{{familyName}}">
</div>
:
<div class="entry">
<label>Full name:</label>
<input disabled type="text" value="{{fullName}}" >
</div>
:
</div>
<template>
</polymer-element>
The code for the form properties, the things Polymer-dart binds to the HTML with the moustache syntax, "{{fullName}}". To keep things simple, I used just one 'notifier' field and this updates the fullName field from both familyName and givenName.
reference_form.dart:
//---- testing ----
String _familyName; // (1)
#observable // (2)
String get familyName => _familyName; // (3)
void set familyName( String nam ){ // (4)
_familyName = nam;
fullName = notifyPropertyChange( // (5)
#fullName,
"${fullName}",
"${nam}, ${theData['givenName']}" );
}
#observable
String fullName; // (6)
//---- end: testing ----
The private member, "_familyName", is a shadow for the public familyName property used in the template (snippet above).
Shadow (private) member, "_familyName", stores the data for the familyName pseudo property.
The next three lines declare an #observable property, familyName
Get familyName. Simply echo the value for the shadow variable.
Set familyName. Updates the shadow variable and the composite fullName property.
Note: the composit formatting could be done with two lines: _familyName = nam; fullName = nam; ... But we want to see all changes propagated see (#5).
The notifyPropertyChange() method updated all observers of the fullName property.
Note: I didn't hack around inside Polymer itself; inside the Observable class, fullName doesn't has no observers with the code shown.
Until I saw this, I assumed that the Polymer binding to the HTML template was via an observer (watcher), it would seem not. I may be mistaken. In any case, the call to notifyPropertyChange() for the '#fullName' symbol didn't change the results for this test case.
fullName property bound to the Polymer form.
Basically the {{fullName}} value will be updated every time there's a change to the familyName pseudo property.
Note on efficiency:
The familyName setter is called with every keystroke (observed while debugging). I understand that, and suggest it is not always really the best solution.
For me, I'd prefer to only call the setter when a user exits the field. However when I used onblur, the trigger was a blur of the form, not the field.
It seems that we might all benefit in terms of performance with a bit more insider information about these hooks, pathways and any options available to make things more efficient.
Comments and improvements welcome. This example is a workaround for me, so its definitely a work in progress. ;-)
Encapsulation method
I am evolving a solution closer to the original ambition and based on the 'observer method' above. This approach relies on the current, i.e. Dart v4, use of modules and libraries. I'll show the working code first and explain interesting stuff with notes.
reference_form.dart:
import 'package:exportable/exportable.dart'; // [1]
class _Data // [2]
extends Object with Exportable { // [3]
#export String publishDate; // [4]
#export String authorGivenName = '(given)';
#export String authorFamilyName = '(family)';
#export String authorUrl = '';
//--- attributes ---
String get fullName => "${authorFamilyName}, ${authorGivenName}"; // [5]
void set fullName( String nam ){ // [6]
//don't need this
}
//--- ctor ---
_Data(){
publishDate = new DateTime.now().toString(); // [7]
}
} //_Data
#CustomTag('reference-form')
class SlamBookComponent extends FormElement with Polymer, Observable {
SlamBookComponent.created() : super.created();
//---- testing ----
#observable
_Data data = new _Data(); // [8]
:
} //SlambookComponent
Notes:
Include Exportable mixin to convert to JSON. I'm not exporting 'fullName' because it is just formatting at the moment.
Add exportable to your pubspec.yaml and 'Run Pub get'.
The "_Data" class is private to the reference_form.dart module. I did a bit of testing of the scope rules because I do not want the internal data structure to leak, except for something catholic like JSON of course (small-c).
Bring-in the Exportable mixin.
I have tested Exportable, it implements exactly what I thought I'd have to write myself. Happy with this.
JSON is not a requirement of the original question; but I did want the (eventual) solution to be a first class artefact that can be serialized or saved is important in the majority of my use-cases.
This is a very good example of the facility to extend Dart quick and agile!
Use the #export modifier to identify fields specific to be interchanged as JSON.
Export the fullName attribute as a String (get).
There is no need for set operation. However Dart apparently insists that a Set method matches 'get'.
I am disappointed by this. I much prefer the idea that I can have READ-ONLY properties and attributes, e.g. like ruby.
As tested, Dart SDK v1.4.0; fails when a matching setter is not implemented/declared(??).
Use a constructor to set initial values for Date data attribute.
Declares an opaque public property called "data", as an (private) _Data instance.
The data formatting of key fields is encapsulated in the private _Data declaration.
The Exportable mixin interface is used to map the private class to a public JSON result.
Point #8 demonstrates a powerful aspect of dart, to enable an opaque implementation of objects and yet, you can 'deliver'/'share' details without specific internal details.
I have run this code and checked that the concepts work for hidden data (the _Data type) and opaque access and serialisation. Also you can't accidentally look at internal private type (accidentally, although explicit hacks may be possible). I don't apologise for accepting the C / C++ conscious responsibility paradigm -- I think this a the most powerful aspect of being a programmer; WE are responsible for effects/bugs stemming from the code we produce. I recommend testing 'bits of behaviour' in small mini-use-cases.
I put examples of the polymer markup; nothing surprising. For me this approach is less verbose and a bit more Object Oriented than the original (early) Dart tutorial
reference_form.html
<polymer-element name="reference-form" extends="form" >
<template>
<style> ... </style>
<div id="slambookform" >
<div class="entry">
<label>Author:</label>
<input type="text" value="{{data.authorGivenName}}" >
<input type="text" value="{{data.authorFamilyName}}">
</div>
<div class="entry">
<label>Published:</label>
<input type="date" value="{{data.publishDate}}">
</div>
</div>
</template>
<script type="application/dart" src="reference_form.dart"> </script>
</polymer-element>
In the Polymer mark-up can know (and has visibility over) internal field names. Why?
... Because the "reference_form.html" and "reference_form.dart" via Polymer-dart. It is quite nice really; although it seems that the ".dart" and ".html" components are closely coupled like ASP.NET and C#/VN.NET as (also) specified by convenience(??). I confess that's a completely different subject; there are things to resolve to keep things yar (yachting term).
Anyway for me, I feel the approach begun with the encapsulation shamble above is better suited to my needs for a small utility.
Polymer now supports this use case directly with #ObserveProperty
#observable String authorGivenName = '';
#observable String authorFamilyName = '';
#observable String get fullName => '${authorGivenName} ${authorFamilyName}';
#ObserveProperty('authorGivenName authorFamilyName')
void updateFullName(old) {
notifyPropertyChange(#fullName, old, fullName);
}

ASP.NET MVC 3 - Add/Remove from Collection Before Posting

I have a model that contains a collection, such as this:
class MyModel
{
public List<MySubModel> SubModels { get; set; }
}
In the view, I want to dynamically add/remove from this list using Javascript before submitting. Right now I have this:
$("#new-submodel").click(function () {
var i = $("#submodels").children().size();
var html = '<div>\
<label for="SubModels[' + i + '].SomeProperty">SomeProperty</label>\
<input name="SubModels[' + i + '].SomeProperty" type="textbox" />\
</div>'
$("#submodels").append(html);
});
This works, but it's ugly. And, if I want to show those labels/textboxes for the existing items, there's no clean way to do that either (without duplicating).
I feel like I should be able to use Razor helpers or something to do this. Any ideas? Help me stay DRY.
You approach may lead to unexpected errors if you when you are removing or adding the divs. For example you have 4 items, you remove the first item, then $('#submodels').children().size() will return 3, but your last inserted div has the name attribute value set SubModels[3].SomeProperty which results in a conflict. And if your posted values contain SubModels[1] but not SubModels[0] the default model binder will fail to bind the list (it will bind it as null). I had to learn this the hard way...
To eliminate the aforementioned problem (and your's) I suggest you do something like this:
$("#addBtn").click(function() {
var html = '<div class="submodel">\
<label>SomeProperty</label>\
<input type="textbox" />\
</div>'; // you can convert this to a html helper!
$("#submodels").append(html);
refreshNames(); // trigger after html is inserted
});
$(refreshNames); // trigger on document ready, so the submodels generated by the server get inserted!
function refreshNames() {
$("#submodels").find(".submodel").each(function(i) {
$(this).find("label").attr('for', 'SubModels[' + i + '].SomeProperty');
$(this).find("label").attr('input', 'SubModels[' + i + '].SomeProperty');
});
}
Then your view (or even better an EditorTemplate for the SubModel type) can also generate code like:
<div class="submodel">
#Html.LabelFor(x => x.SomeProperty);
#Html.EditorFor(x => x.SomeProperty);
</div>
It would also be possible to convert the code generation to a html helper class, and use it in the EditorTemplate and in the JavaScript code
I would recommend you going through the following blog post.

.NET MVC View question

I have this cute little progress bar looking thing in a dashboard page. Once it is started up, it updates itself every minute via ajax, javascript, blah, blah. Since some of my viewers are looking at it on older Blackberries, I normally figure out how big the bar should be for the initial rendering server-side, and draw the page accordingly, then let the javascript take over after that, on those viewers that have it.
The old code, plain old ASP.NET has an asp:Label in the page where the img tag goes, and on the server I cat together the whole thing. As I refactor to an MVC way of looking at things, I thought how wonderful it would be to only write the width style attribute of the image on the server. The code on the page would be a good deal more understandable that way.
But it doesn't work. Example:
<img src="/content/images/blue_1px.png" class="productionBar_variableBar"
style="width: <% =dbd["ThisShiftProduction_variableBar"] %>;"/>
Unfortunately, Visual Studio doesn't seem to recognize the <% %> escape inside of the quoted style attribute.
Any suggestions?
Siggy
The simplest way - creating HtmlHelper extension:
public static class Html
{
public static string ProgressBar(this HtmlHelper html, int width)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("img src=\"/content/images/blue_1px.png\" class=\"productionBar_variableBar\" style=\"width: {0};\" />", width);
return sb.ToString();
}
// OR
public static string ProgressBar(this HtmlHelper html, int width, string src, string cssClass)
{
TagBuilder tagBuilder = new TagBuilder("img");
tagBuilder.AddCssClass(cssClass);
tagBuilder.MergeAttribute("style", "width: " + width.ToString());
string srcUrl = new UrlHelper(html.ViewContext.RequestContext).Content(src);
tagBuilder.MergeAttribute("src", srcUrl);
return tagBuilder.ToString(TagRenderMode.Normal);
}
}
Using it:
<%= Html.ProgressBar(dbd["ThisShiftProduction_variableBar"]) %>
<!-- OR -->
<%= Html.ProgressBar(dbd["ThisShiftProduction_variableBar"], "~/content/images/blue_1px.png", "productionBar_variableBar") %>
Have you tried doing this instead
<img src="/content/images/blue_1px.png" class="productionBar_variableBar" style='width: <% =dbd["ThisShiftProduction_variableBar"] %>;'/>
Notice the single quotes instead of the double quotes in the style attribute

Resources