To avoid repeat re-writing the same code multiple times,I'm using VueJs component feature to make a component that includes the Select dropdown list.
The code goes like this
Vue.component('select-component', {
template: `
<label>elType</label>
<div class="col-md-colwidth">
<select>
<option value=""></option>
#foreach (elType s in ViewBag.elTypes)
{
<option value="#s[elType+"ID"]">#s["Designation"+elType]</option>
}
</select>
<input type="hidden" v-model="elTarget">
</div>
`,
props: {
elType: {
type: String,
default: 'User'
},
elTarget: {
type: String,
default: 'user'
},
colwidth: {
type: int,
default: '3'},
}
})
As you can see, I'm requiring some data list I brought from the ViewBag
but all i get is that the Razor is always ignoring that it is inside a Vue Component and giving "The type or namespace name 'elType' could not be found ".
P.S:
1) the input Hidden is used in the original code to manipulate the bs jQuery select2
2)Don't mind the elTarget and elType :p it's actually same thing except I'm lazy to camelCase the word :p
3)I tried to wrap the inside #{ } but still toggle the same error
You can't use Razor 'inside' a Vue component because Razor generates the page server-side before Vue gets to do its stuff in the browser. What you have there is a Vue component inside a Razor page. elType is defined as a Vue prop, so it likely isn't in your view bag?
In any case, please don't do this! Use Razor or Vue. If you choose Vue, your vue components are static .js or .vue files, your data arrives via AJAX calls, and you loop through elTypes with v-for, in the browser. Any other way will lead to madness :-)
You could send your razor with props to the component if necessary:
View file
<component-name :prop1="#Model.somethingOtherThanString" prop2="#Model.aString"></component-name>
Vue file
props: {
prop1: Boolean,
prop2: String
}
Related
I have a set of form fields that are in a dynamically created component. The parent Component owns the form tag. However, none of the form fields are being added to the Form. I'm using the ComponentFactoryResolver to create the component:
#Component({
selector: 'fieldset-container',
templateUrl: './fieldset-container.component.html',
styleUrls: ['./fieldset-container.component.scss'],
entryComponents: ALL_FIELD_SETS,
})
export class FieldsetContainerComponent<C> {
fieldsetComponent : ComponentRef<any> = null;
#Input() formGroup : FormGroup;
#ViewChild('fieldSetContainer', {read: ViewContainerRef})
fieldsetContainer : ViewContainerRef;
#Output() onComponentCreation = new EventEmitter<ComponentRef<any>>();
constructor(private resolver : ComponentFactoryResolver) {
}
#Input() set fieldset( fieldset : {component : any, resolve : any }) {
if( !fieldset ) return; // sorry not right
// Inputs need to be in the following format to be resolved properly
let inputProviders = Object.keys(fieldset.resolve).map((resolveName) => {return {provide: resolveName, useValue: fieldset.resolve[resolveName]};});
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
// We create an injector out of the data we want to pass down and this components injector
let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.fieldsetContainer.parentInjector);
// We create a factory out of the component we want to create
let factory = this.resolver.resolveComponentFactory(findComponentForFieldset(fieldset.component));
// We create the component using the factory and the injector
let component : ComponentRef<any> = factory.create(injector);
// We insert the component into the dom container
this.fieldsetContainer.insert(component.hostView);
// Destroy the previously created component
if (this.fieldsetComponent) {
this.fieldsetComponent.destroy();
}
this.fieldsetComponent = component;
this.onComponentCreation.emit( this.fieldsetComponent );
}
}
The template:
<div #fieldSetContainer [formGroup]="formGroup"></div>
The usage of the dynamic component:
<form class="form" #omaForm="ngForm">
<div *ngFor="let fieldset of page?.fieldsets">
<fieldset-container [fieldset]="{ component: fieldset, resolve: {} }" (onComponentCreation)="onComponentCreation($event)" [formGroup]="omaForm.form"></fieldset-container>
</div>
</form>
I suspect it has something to do with the injector not being hooked up correctly, but from what I can tell it is chained to the parent. I've set a breakpoint in NgModel and it is passed a null for parent which is the problem. I traced that back up into something that looks compiled and it was just hard coding a null. So I'm not sure how that was created with hard coded nulls in there.
Any ideas on how to fix this?
Ok it turns out it has nothing to do with the dynamic nature of this component. I removed it and defined all of my components inline and it still had the problem. The issue was that having form controls inside a Component that were nested within a form tag is just not supported by Angular out of the box. Once you nest a form control in a component it can't see the NgForm anymore which is crazy.
After reading solutions on the web and seeing that no one had a good solution I designed 2 of my own directives that registered the Form into the DI container up at the NgForm, then using DI hierarchy I could inject that into another Directive that would perform the registration below.
Parent Component Template:
<form nested>
<my-component .../>
</form>
Child Component Template:
<div>
<input name="street" [(ngModel)]="address.street" required nest/>
<input name="city" [(ngModel)]="address.city" required nest/>
<input name="state" [(ngModel)]="address.state" required nest/>
<input name="zip" [(ngModel)]="address.zip" required nest/>
</div>
Once I had this in place then I could bring back my dynamic component and it worked perfectly. It was just really hard to get there.
It's really elegant and simple and doesn't require me to pass the form instance down through the layers like so many suggestions on the web show. And the work to register a form control whether it's 1 layer or 999 layers removed is the same.
IMHO NgForm and NgModel should just do this out of the box for us, but they don't which leads to complicated architecture design to accomplish moderately advanced forms.
I am working on replacement ASP.NET MVC+Knockout with just Knockout, I want to remove ASP.NET and get just static js + html.
My ASP.NET views consist of Partial views (I call them widgets in my project), this Partial views easily replaced with Knockout components.. but I have a problem: ASP.NET Partial views have a Layout (some html decoration for every widget), how can I achieve similar for Knockout component view?
Simplified example. Old asp.net scheme:
View.cshtml:
<div>
#Html.Partial("SomeWidget")
</div>
SomeWidget.cshtml:
#{
Layout = "~/Views/Shared/_WidgetLayout.cshtml"; <!-- parent layout for widget -->
}
<span>This is some widget</span>
_WidgetLayout.cshtml:
<div>
<span>This is decorator for every widget</span>
#RenderBody() <!-- render widget view here (SomeWidget.cshtml in this example) -->
</div>
New knockout-only scheme:
View.html:
<div>
<some-widget></some-widget>
</div>
View.js:
ko.components.register('some-widget', { require: 'app/SomeWidget' });
SomeWidget.html:
<span>This is some widget</span>
SomeWidget.js:
var view = require('text!/views/SomeWidget.html');
return { template: view };
How to replace _WidgetLayout.cshtml in Knockout?
There are several ways you could possibly do this. The simplest way I can think of is to have a template component, and you nest the widget inside this. KO Components support nesting.
You can define a template component thus:
ko.components.register("widget-template", {
viewModel: function(params) {
var self=this;
self.WidgetName = params.widget;
},
template: "<div class='b'><span>This is decorator for every widget</i>
<div data-bind='component: { name: WidgetName }'></div></div>"
});
To use this, you put the template-widget into your HTML, and pass the name of the widget as a parameter:
<widget-template params="widget: 'widget1'"></widget-template>
Then you define a widget as another component:
ko.components.register("widget1", {
template: "<h3>Widget One</h3>"});
So now you have a re-usable template that can wrap any component. You can see more about this binding in the Knockout documentation.
See the full JS fiddle here: http://jsfiddle.net/Quango/a8h2bwtc/
Note that you can also make the name an observable rather than a static value, as seen here:
http://jsfiddle.net/Quango/tnphvvgd/
I'm trying to create a image upload with the kendo editor.
I'm always getting an error:
ReferenceError: uid is not defined
...==E&&(E=1),g?(b&&(A+=-b),w&&(I+=-w),e=new
Date(Date.UTC(F,D,E,A,I,H,N))):(e=new ...
kendo.web.min.js (Zeile 11)
I'm using jQuery 1.8.3 and kendoui.web.2013.1.319.open-source
My code is as follow:
<div id="example" class="k-content">
<textarea id="editor" rows="10" cols="30" name="reply-content"></textarea>
</div>
<script>
$(document).ready(function () {
$("#editor").kendoEditor({
imageBrowser: {
messages: {
dropFilesHere: "Drop files here"
},
transport: {
read: "/images/ImageBrowser/Read",
destroy: "/images/ImageBrowser/Destroy",
create: "/images/ImageBrowser/Create",
thumbnailUrl: "/images/ImageBrowser/Thumbnail",
uploadUrl: "/images/ImageBrowser/Upload",
imageUrl: "/images/ImageBrowser/Image?path={0}"
}
}
});
});
</script>
Has someone experienced the same issue?
You are probably returning a list of string, but the editor is waiting for an json result (name, type, size). You can check the demo with a sniffer to see what kind of results is expected from read/thumbnail, etc. Not very sure if you really must implement an server class for Kendo's client equivalent, but, by default, the result for Read is expected as Json for sure.
New finaly i got it to work. I used some workarounds but see your self.
You can also test the functionality on the site: http://jonas.dnsd.me/forum/topic?id=113
But stil it has some bugs like the url: /imageBrowser/?path=/image.jpg. I remove '/?path=' with a javascript function, but it works just for 3 images.
If you upload a image the window will not refreseh.
I would appreciate some ideas about the issues.
Now it is working like a charm ... see at http://jonas.dnsd.me/forum/topic?id=113
I updated to new source code
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.
I'm just now starting to learn ASP.NET MVC. How would I go about creating a reusable tri-state checbox? In WebForms this would be a control, but I don't know the MVC equivalent.
Add a TriStateCheckBox (or TriStateCheckBoxFor if you use the strongly typed overloads) extension method to HtmlHelper and add the namespace of that extension method class to the namespaces section of your web.config.
As for the implementation, I'd recommend having at look at the InputExtensions source on codeplex and using that to create your own.
Limitations:
View Rendering - When rendering HTML content, there is no attribute you can possibly place on an <input type="checkbox" /> that will give it the property indeterminate.
At some point, you'll have to use JavaScript to grab the element and set the indeterminate property:
// vanilla js
document.getElementById("myChk").indeterminate = true;
// jQuery
$("#myCheck).prop("indeterminate", true);
Form Data - model binding will always be limited to what values are actually sent in the request, either from the url or the data payload (on a POST).
In this simplified example, both unchecked and indeterminate checkboxes are treated identically:
And you can confirm that for yourself in this Stack Snippet:
label {
display: block;
margin-bottom: 3px;
}
<form action="#" method="post">
<label >
<input type="checkbox" name="chkEmpty">
Checkbox
</label>
<label >
<input type="checkbox" name="chkChecked" checked>
Checkbox with Checked
</label>
<label >
<input type="checkbox" name="chkIndeterminate" id="chkIndeterminate">
<script> document.getElementById("chkIndeterminate").indeterminate = true; </script>
Checkbox with Indeterminate
</label>
<label >
<input name="RegularBool" type="checkbox" value="true">
<input name="RegularBool" type="hidden" value="false">
RegularBool
</label>
<input type="submit" value="submit"/>
</form>
Model Binding - Further, model binding will only occur on properties that are actually sent. This actually poses a problem even for regular checkboxes, since they won't post a value when unchecked. Value types do always have a default value, however, if that's the only property in your model, MVC won't new up an entire class if it doesn't see any properties.
ASP.NET solves this problem by emitting two inputs per checkbox:
Note: The hidden input guarantees that a 'false' value will be sent even when the checkbox is not checked. When the checkbox is checked, HTTP is allowed to submit multiple values with the same name, but ASP.NET MVC will only take the first instance, so it will return true like we'd expect.
Render Only Solution
We can render a checkbox for a nullable boolean, however this really only works to guarantee a bool by converting null → false when rendering. It is still difficult to share the indeterminate state across server and client. If you don't need to ever post back indeterminate, this is probably the cleanest / easiest implementation.
Roundtrip Solution
As there are serious limitations to using a HTML checkbox to capture and post all 3 visible states, let's separate out the view of the control (checkbox) with the tri-state values that we want to persist, and then keep them synchronized via JavsScript. Since we already need JS anyway, this isn't really increasing our dependency chain.
Start with an Enum that will hold our value:
/// <summary> Specifies the state of a control, such as a check box, that can be checked, unchecked, or set to an indeterminate state.</summary>
/// <remarks> Adapted from System.Windows.Forms.CheckState, but duplicated to remove dependency on Forms.dll</remarks>
public enum CheckState
{
Checked,
Indeterminate,
Unchecked
}
Then add the following property to your Model instead of a boolean:
public CheckState OpenTasks { get; set; }
Then create an EditorTemplate for the property that will render the actual property we want to persist inside of a hidden input PLUS a checkbox control that we'll use to update that property
Views/Shared/EditorTemplates/CheckState.cshtml:
#model CheckState
#Html.HiddenFor(model => model, new { #class = "tri-state-hidden" })
#Html.CheckBox(name: "",
isChecked: (Model == CheckState.Checked),
htmlAttributes: new { #class = "tri-state-box" })
Note: We're using the same hack as ASP.NET MVC to submit two fields with the same name, and placing the HiddenFor value that we want to persist first so it wins. This just makes it easy to traverse the DOM and find the corresponding value, but you could use different names to prevent any possible overlap.
Then, in your view, you can render both the property + checkbox using the editor template the same way you would have used a checkbox, since it renders both. So just add this to your view:
#Html.EditorFor(model => model.OpenTasks)
The finally piece is to keep them synchronized via JavaScript on load and whenever the checkbox changes like this:
// on load, set indeterminate
$(".tri-state-hidden").each(function() {
var isIndeterminate = this.value === "#CheckState.Indeterminate";
if (isIndeterminate) {
var $box = $(".tri-state-box[name='" + this.name + "'][type='checkbox']");
$box.prop("indeterminate", true);
}
});
// on change, keep synchronized
$(".tri-state-box").change(function () {
var newValue = this.indeterminate ? "#CheckState.Indeterminate"
: this.checked ? "#CheckState.Checked"
: "#CheckState.Unchecked";
var $hidden = $(".tri-state-hidden[name='" + this.name + "'][type='hidden']");
$hidden.val(newValue);
});
Then you can use however you'd like in your business model. For example, if you wanted to map to a nullable boolean, you could use the CheckState property as a backing value and expose/modify via getters/setters in a bool? like this:
public bool? OpenTasksBool
{
get
{
if (OpenTasks == CheckState.Indeterminate) return null;
return OpenTasks == CheckState.Checked;
}
set
{
switch (value)
{
case null: OpenTasks = CheckState.Indeterminate; break;
case true: OpenTasks = CheckState.Checked; break;
case false: OpenTasks = CheckState.Unchecked; break;
}
}
}
Alternative Solution
Also, depending on your domain model, you could just use Yes, No, ⁿ/ₐ radio buttons
ASP.NET MVC certainly doesn't provide such component, actually it simply relies on the standard elements available in HTML but you may want to check out this solution.