Model data not binding to html template in Backbone,Marionette - asp.net-mvc-4

I am new to backbone and Marionette.
My requirement is,
I have a main grid having few rows. If i select a row from grid i need to fetch the details and display on the same page.
Binding the grid is working fine. But when i click on the row data is not binding to html template. I am unable to find out the issue.
Below is my html template for row details
<script id="selected-broker-details-tmpl" type="text/x-handlebars-template">
<div id="pnl-broker-details" class="panel panel-default">
<div class="panel-heading">
Broker Details
</div>
<div id="broker-details-container" class="panel-body">
<div class="col-md-6">
<div class="form-group">
<label for="inputbrokerName" class="col-sm-3 control-label">BrokerName</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputbrokerName" placeholder="Broker Name" value="{{BrokerName}}">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="inputMnemonic" class="col-sm-3 control-label">Mnemonic</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputMnemonic" placeholder="Mnemonic" value="{{Mnemonic}}">
</div>
</div>
</div>
</div>
</div>
</script>
Backbone view declaration
App.Views.BrokerDetails = Backbone.View.extend({
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
el: '#details',
template: brokerTemplates.BrokerDetailsTempalte,
render: function () {
this.$el.html(this.template({}));
}
});
Model and collection declaration
var BrokderDetails = Backbone.Model.extend({
BrokerId: null,
BrokerName: null,
Mnemonic: null,
OASYSMnemonic: null
});
var BrokerDetailsCollection = Backbone.Collection.extend({
initialize: function (options) {
this.model = BrokderDetails;
this.url = '/api/BrokerSelections/SelectedBroker/';
}
,
setParam: function (str) {
this.url = '/api/BrokerSelections/SelectedBroker/' + str;
this.fetch();
},
parse: function (data) {
return data;
}
});
click event in main grid
events: {
"click .selection": "selectedBroker",
},
selectedBroker: function (e) {
var details = new BrokerDetailsCollection();
var brokerdetails = new App.Views.BrokerDetails({ model: null, collection: details });
details.setParam($(e.currentTarget).data("id"));
details.fetch();
brokerdetails.render();
},
Now there are 2 issues,
1. Click event is firing 2 times, if i select a row i main grid
2. Model data is not binding to html template. I mean html template is displayed, but with empty values in textboxes

Related

Files From Upload Modal Not Being Passed

I have a BootStrap Modal Popup that I want to use for selecting and uploading a file. The pop-up works in all respects EXCEPT it is not passing the selected file to the underlying controller. Here is the form:
<!--Modal Body Start-->
<div class="modal-content">
<!--Modal Header Start-->
<div class="modal-header">
<h4 class="modal-title">Upload File</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!--Modal Header End-->
<form asp-action="FileUpload" asp-controller="Attachment" method="post" enctype="multipart/form-data">
#Html.AntiForgeryToken()
<div class="modal-body form-horizontal">
<div>
<p>Upload a file using this form:</p>
<input type="file" name="file" />
</div>
<!--Modal Footer Start-->
<div class="modal-footer">
<button data-dismiss="modal" id="cancel" class="btn btn-default" type="button">Cancel</button>
<input type="submit" class="btn btn-success relative" id="btnSubmit" data-save="modal" value="Upload">
</div>
<div class="row">
</div>
</div> <!--Modal Footer End-->
</form>
</div>
<script type="text/javascript">
$(function () {
});
</script>
<!--Modal Body End-->
Here is the action in the controller:
[HttpPost]
public IActionResult FileUpload(IFormFile file)
{
//DO something with the file
return View();
}
[HttpGet]
public ActionResult UploadFile(string issueid)
{
ViewBag.id = issueid;
return PartialView("_UploadFile");
}
The action gets called but the "file" variable is NULL.
I have the following markup & script on the MAIN page the pop-up originates from:
<div id="modal-container" class="modal fade" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
</div>
</div>
</div>
Upload Files
<script>
$('body').on('click', '.modal-link', function () {
var actionUrl = $(this).attr('href');
$.get(actionUrl).done(function (data) {
$('body').find('.modal-content').html(data);
});
$(this).attr('data-target', '#modal-container');
$(this).attr('data-toggle', 'modal');
});
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = form.serialize();
$.post(actionUrl, dataToSend).done(function (data) {
$('body').find('.modal-content').html(data);
});
})
$('body').on('click', '.close', function () {
$('body').find('#modal-container').modal('hide');
});
$('#CancelModal').on('click', function () {
return false;
});
$("form").submit(function () {
if ($('form').valid()) {
$("input").removeAttr("disabled");
}
});
</script>
To upload form data with a file you have to use a FormData object.
Also, you have to use $.ajax, as $.past cannot handle the FormData object
$('body').on('click', '.relative', function (e) {
e.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = new FormData(form[0]);
$.ajax({
url: actionUrl,
type: 'POST',
data: dataToSend,
processData: false, //prevent jQuery from trying to serialize the FormData object
contentType: false, // prevents jQuery from setting the default content type
success: function(data){
$('body').find('.modal-content').html(data);
}
});
})

Method Updating Data Twice on Form Submission

I have a component that is a form that I input a name and it updates a value on a field on the backend based on which input the name is. Right now I have two inputs (host and scout) and they work fine if I just fill one input. My problem is, when I fill both inputs, the name on the host input will always get updated twice while the name on the scout field will work just fine. Not sure if I was clear enough.
Here is the code for the component so far
<template>
<div class="add-wave">
<h3>Add Wave</h3>
<div class="row">
<form #click.prevent="addwave()" class="col s12">
<div class="row">
<div class="input-field col s12">
<input type="text" v-model="host" />
<label class="active">Host</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" v-model="scout" />
<label class="active">Scout</label>
</div>
</div>
<button type="submit" class="btn">Submit</button>
<router-link to="/member" class="btn grey">Cancel</router-link>
</form>
</div>
</div>
</template>
<script>
import { db, fv } from "../data/firebaseInit";
export default {
data() {
return {
host: null,
scout: null
};
},
methods: {
addwave() {
this.addhost();
db.collection("members")
.where("name", "==", this.scout)
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
doc.ref.update({
scout: fv.increment(1),
total: fv.increment(1)
});
});
});
},
addhost() {
db.collection("members")
.where("name", "==", this.host)
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
doc.ref.update({
host: fv.increment(1),
total: fv.increment(1)
});
});
});
}
}
};
</script>
I'm not sure why is it updating twice only when I fill both input fields.

Click Event on Dynamically Generated Button Don't get fired in Vue

I am adding a button dynamically and attaching the click event but it doesn't seem to fire.
I see something similar on link below but its not exactly what I am looking for.
Vue: Bind click event to dynamically inserted content
let importListComponent = new Vue({
el: '#import-list-component',
data: {
files: [],
},
methods: {
// more methods here from 1 to 5
//6. dynamically create Card and Commit Button
showData: function (responseData) {
let self = this;
responseData.forEach((bmaSourceLog) => {
$('#accordionOne').append(`<div class="main-card mb-1 card">
<div class="card-header" id=heading${bmaSourceLog.bmaSourceLogId}>
${bmaSourceLog.fileName}
<div class="btn-actions-pane-right actions-icon-btn">
<input type="button" class="btn btn-outline-primary mr-2" value="Commit" v-on:click="commit(${bmaSourceLog.bmaSourceLogId})" />
<a data-toggle="collapse" data-target="#collapse${ bmaSourceLog.bmaSourceLogId}" aria-expanded="false" aria-controls="collapse${bmaSourceLog.bmaSourceLogId}" class="btn-icon btn-icon-only btn btn-link">
</a>
</div>
</div>
<div id="collapse${ bmaSourceLog.bmaSourceLogId}" class="collapse show" aria-labelledby="heading${bmaSourceLog.bmaSourceLogId}" data-parent="#accordionOne">
<div class="card-body">
<div id="grid${ bmaSourceLog.bmaSourceLogId}" style="margin-bottom:30px"></div>
</div>
</div>
</div>`);
});
},
//7. Commit Staging data
commit: function (responseData) {
snackbar("Data Saved Successfully...", "bg-success");
},
}});
I am adding button Commit as shown in code and want commit: function (responseData) to fire.
I was able to achieve this by pure Vue way. So my requirement was dynamically add content with a button and call a function from the button. I have achieved it like so.
Component Code
const users = [
{
id: 1,
name: 'James',
},
{
id: 2,
name: 'Fatima',
},
{
id: 3,
name: 'Xin',
}]
Vue.component('user-component', {
template: `
<div class="main-card mb-1 card">
<div class="card-header">
Component Header
<div class="btn-actions-pane-right actions-icon-btn">
<input type="button" class="btn btn-outline-primary mr-2" value="Click Me" v-on:click="testme(user.id)" />
</div>
</div>
<div class="card-body">
{{user.name}}
</div>
<div class="card-footer">
{{user.id}}
</div>
</div>
`
,props: {
user: Object
}
,
methods: {
testme: function (id) {
console.log(id);
}
}});
let tc = new Vue({
el: '#test-component',
data: {
users
},});
HTML
<div id="test-component">
<user-component v-for="user in users" v-bind:key="user.id" :user="user" />
</div>

How can I pass dynamic data to DOM with Vue.js

In my context, I got dynamic text brought by database (JS file).
But I don't know how to display that data to my HTML dynamicly.
The main ID is when I load the page, It automaticly display data (if there is data) on the "nom" field.
I am new to Vue.js so I'll need your help there, thanks.
Here is my js file :
var ip_adresse = new Vue({
el: "#adresse_ip",
data: {
adresse: [],
},
created() {
this.charger_adresse();
},
methods: {
charger_adresse() { // Méthode
var self = this;
$.get(SITE_URL + '/modules/informations_pratiques/infos_mairie/load_adresse/' + APP_ID, function(reponse) {
console.log(reponse);
self.adresse.nom = reponse[0]['adresse'];
console.log(self);
});
},
}
And here is my HTML :
<article id="adresse_ip">
<form action="">
<div class="row">
<p class="stay-strong">Renseignez l'adresse de la Mairie</p>
<input name="nom" type="text">
</div>
<div class="row submit">
<button class="publish">Enregistrer les informations</button>
</div>
</form>
</article>
You're not binding your input element with the data object, like:
new Vue({
el: '#adresse_ip',
data: {
address: ''
},
created() {
this.charger_adresse();
},
methods: {
charger_adresse() {
//fetch your data via AJAX and set it to the object
this.address = 'foobar'
}
}
})
<script src="https://unpkg.com/vue"></script>
<article id="adresse_ip">
<form action="">
<div class="row">
<p class="stay-strong">Renseignez l'adresse de la Mairie</p>
<input name="nom" type="text" v-model="address" :val="address">
</div>
<div class="row submit">
<button class="publish">Enregistrer les informations</button>
</div>
</form>
</article>
Read more about form input bindings

Why I can not see the data in an input field when I use the knockout with: binding

I want to make a dynamic dialog box. For that I need some data like title, content and viewmodel. The title and the content will be shown. But the viewmodel not bind correctly. To see the problem, I prefilled the first_name with 'foo'. But it should be 'my first name'.
To make the modal dialog dynamic, we have a modalDialog object that must be filled with the specific data. The openDialog function fill this data and open it.
Normally the dynamic part will be load by requirejs. For demonstrate the problem, I have made it here much easier.
Here the html code:
<!-- the dynamic modal dialog -->
<div id="modal-dialog" class="modal fade" role="dialog" data-backdrop="static" data-bind="css: modalDialog.classes">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-bind="click: modalDialog.close">×</button>
<h4 class="modal-title" data-bind="html: modalDialog.title"></h4>
</div>
<div data-bind="with: modalDialog.viewModel">
<div class="modal-body" data-bind="html: $parent.modalDialog.content"></div>
</div>
<div class="modal-footer" data-bind="foreach: modalDialog.buttons">
<button type="button" class="btn btn-primary" data-bind="click: action, text: label"></button>
</div>
</div>
</div>
</div>
<!-- Test button for open the dialog -->
<button type="button" class="btn btn-info" data-bind="click: testDialog">Open modal</button>
Here the javascript code for the modal dialog viewmodel:
// the main viewmodel
var appVM = {
modalDialog:
{
title: ko.observable(''),
content: ko.observable(''),
viewModel: ko.observable(this),
buttons: ko.observableArray([]),
classes: ko.observable(''),
open: function()
{
$("#modal-dialog").modal('show');
},
close: function()
{
$("#modal-dialog").modal('hide');
}
},
openDialog: function(title, content, viewModel, buttons, classes)
{
if (!viewModel)
viewModel = appVM;
if (!buttons)
buttons = [{action: appVM.modalDialog.close, label: 'Close'}];
if (!classes)
classes = '';
appVM.modalDialog.title(title);
appVM.modalDialog.content(content);
appVM.modalDialog.buttons(buttons);
appVM.modalDialog.classes(classes);
appVM.modalDialog.viewModel(viewModel);
appVM.modalDialog.open();
},
testDialog: function()
{
var vm = new userViewModel();
var title = 'Test Title';
var html = dialogContent;
var buttons = [
{ action: vm.onSave, label: 'Apply' },
{ action: appVM.modalDialog.close, label: 'Cancel' }
];
appVM.openDialog(title, html, vm, buttons);
}
};
ko.applyBindings(appVM);
At least the code for the dynamic data:
// the user data
function User(data)
{
var self = this;
self.first_name = ko.observable(data.first_name).extend({required: true});
self.last_name = ko.observable(data.last_name).extend({required: true});
}
// the user viewmodel
function userViewModel()
{
var self = this;
self.user = ko.observable(new User(
{
first_name: 'my first name',
last_name: 'my last name'
}));
self.onSave = function()
{
alert('save data');
};
}
// The loaded content for the dialog
var dialogContent = ' \
<div class="clearfix"> \
<div class="col-xs-12"> \
<div class="row form-group"> \
<label class="col-xs-12 col-sm-4 col-md-3">Vorname:</label> \
<input class="col-xs-12 col-sm-8 col-md-9" type="text" data-bind="textInput: user().first_name" title="" value="foo"/> \
</div> \
<div class="row form-group"> \
<label class="col-xs-12 col-sm-4 col-md-3">Nachname:</label> \
<input class="col-xs-12 col-sm-8 col-md-9" type="text" data-bind="textInput: user().last_name" title=""/> \
</div> \
</div> \
</div> \
';
You can try it here:
http://jsfiddle.net/p8zbfw65/
Update
With the Tip from Roy it works like expected. I inserted the boundHtml binding
ko.bindingHandlers.boundHtml = {
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
const contentHtml = ko.unwrap(valueAccessor());
element.innerHTML = contentHtml;
ko.applyBindingsToDescendants(bindingContext, element)
}
};
and changed the html: $parent.modalDialog.content
to boundHtml: $parent.modalDialog.content
The html binding inserts HTML but does not apply bindings to it. You will need a custom binding handler to do that. I wrote a simple one here.