why the function in side of function wont get called? - asp.net-mvc

i have the following reactjs code to generate two dropdown list where the ddlproducts gets loaded by ddlCategories selection. but when i called the function getDataById() and tried to print the ajax populated array data2 to alert(), there was no alert() there were two alerts none of the alerts were prompted. it shown this error message on the IE console,
execution did not reached the function getDataById() 'cus the alert() in that function even didn't execute
SCRIPT438: Object doesn't support property or method 'getDataById'
correction: once the calling of this.props.getDataById() was changed to this.getDataById() it worked
but how do populate the ddlProducts dropdown. how do i access tag of the ddlProducts and then add the options to it?
here is the code:
var gdata=[];
var trStyle = {
'color': 'black',
'border-style' :'solid',
'margin-left':'20%'
};
var HCOMP = React.createClass({
getInitialState:function(){
return{data1:[], data2:[], isMounted:false, selectedValue:0}
},
componentDidMount:function(){
this.getData();
this.setState({isMounted:true})
},
ddlProdCatsChanegeEvent: function(e) {
if (this.state.isMounted)
{
var newV = ReactDOM.findDOMNode(this.refs.refProdCats).value;
var seleValue = newV;
this.setState({selectedValue:newV}, function(){
this.getDataById(this.state.selectedValue);
alert(this.state.data2);
});
}
},
render: function() {
var prodCats = this.state.data1.map(function(ele, index){// <PRODCATSOPTION optValue={ele.ProductCategoryID} optText={ele.Name} />
return <option value={ele.ProductCategoryID} data-key={index}>{ele.Name}</option>
});
prodCats.unshift(<option value={''}>{'---- select category ------'}</option>)
return (<div>Prodcut Category:<br /><select id="ddlCategories" ref="refProdCats" onChange={this.ddlProdCatsChanegeEvent}>{prodCats}</select><br />
Products:<br /><select id="ddlPorducts" ref="refProds"></select><br /></div>
)
},
getDataById:function(catId){
var x = catId;
alert('rec id:'+x);
$.ajax({
url:'http://localhost:53721//Home/GetProductCats?id='+ x,
method:'GET',
success:function(d1){
this.setState({data2:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
},
getData:function(){
//ajax here
$.ajax({
url:'http://localhost:53721//Home/GetProductCats',
method:'GET',
success:function(d1){
this.setState({data1:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
}
});
var PRODOPTIONS = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
var PRODCATSOPTION = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
ReactDOM.render( <HCOMP/>, document.getElementById('d1') );

Try updating ddlProdCatsChanegeEvent to ddlPropCatsChangeEvent.

Related

How I use ReactDOM.findDOMNode() in react for front-end on ruby on rails

var SearchForm = React.createClass({
handleSearch: function() {
alert('sd');
var query = ReactDOM.findDOMNode(this.refs.query).value;
alert(query);
var self = this;
alert('Dom');
$.ajax({
url: '/api/events/search',
data: { query: query },
success: function(data) {
self.props.handleSearch(data);
},
error: function(xhr, status, error) {
alert('Search error: ', status, xhr, error);
}
});
},
render: function() {
return(
<input onChange={this.handleSearch}
type="text"
className="form-control"
placeholder="Type search phrase here..."
ref="query" />
)
}
});
It's content of search_form.js.jsx
But if I run the app, ReactDOM.findDOMNode() doesn't work.
So therefore, alert(query) doesn't rise up.
Who answer to me?
Any reason why you're not using the state or props (in this case you'd lift up the state). One possible solution would be to add the query value as part of the state and change it on each change event. You can find a code example here
var SearchForm = React.createClass({
getInitialState() {
return {
query: ''
}
},
...
render: function() {
return(
<input onChange={this.handleSearch}
type="text"
className="form-control"
placeholder="Type search phrase here..."
value={this.state.query} />
)
}
});
I guess it should be this.refs not this.ref
var query = ReactDOM.findDOMNode(this.refs.query).value;
you can also try to get the value directly:
var query = this.refs.query.value;

React / Rails : Append dynamically element to DOM

Currently following facebook tutorial on React (react_tuto).
I don't understand how 2 components can communicate so that on "submit a comment button" it appends dynamically the "comment list".
currently, comment are created on server but appears on page only when page refreshed
how can the comment appear on submit button?
This i my AddComment component
var AddComment = React.createClass({
getInitialState: function(){
return {
content: this.props.content,
adrien: "before"
}
},
handleKeyUp: function(e) {
this.setState({
content: this.refs.addComment.getDOMNode().value,
})
},
handleValidation: function() {
var that = this
$.ajax({
type: "POST",
data: {comment: { content: that.state.content } },
url: Routes.create_comment_path({format: 'json'}),
success: function(data) {
that.setState({
content: "",
adrien: "after"
})
}
})
},
render: function(){
return (
<div>
<textarea onKeyUp={this.handleKeyUp} value={this.state.value} ref="addComment"></textarea>
<button onClick={this.handleValidation}>submit</button>
</div>
)
}
})
This is my CommentList component:
var CommentList = React.createClass({
render: function() {
return (
<div>
{this.props.comments.map(function(comment){
return <CommentListElement key={comment.id} comment={comment} />;
})}
</div>
);
}
});
You need a common parent component for communication between different components.
I have updated you example a bit to include common parent component CommentSystem
Note: I have removed ajax call to just show the communication between component.
Check below link.
https://jsfiddle.net/j4yk3pzc/15/
Extra Info:
In react we store states on parent component and pass them down to children. Along with state we also pass actions to manipulate data down to the children. When child component want's to update data passed to it from parent, then it fires the action passed from the parent. This is called Data down action up approach. Data is passed from parent to child to grandchild. While actions are propagated from grandchild to child to parent.
If you don't want to create the parent component then you can use some Publish / Subscribe or EventEmitter based system to communicate between children having no common parent.
Reference:
http://ctheu.com/2015/02/12/how-to-communicate-between-react-components/
Code:
var CommentSystem = React.createClass({
getInitialState: function() {
return {
comments: []
}
},
addComments: function(comment) {
var comments = this.state.comments;
comments.push(comment);
this.setState({comments: comments})
},
render: function() {
return (
<div>
<AddComment addComments={this.addComments}/>
<CommentList comments={this.state.comments}/>
</div>
)
}
})
var AddComment = React.createClass({
getInitialState: function(){
return {
content: this.props.content,
adrien: "before"
}
},
handleKeyUp: function(e) {
this.setState({
content: this.refs.addComment.getDOMNode().value,
})
},
handleValidation: function() {
var that = this;
this.props.addComments(this.state.content);
},
render: function(){
return (
<div>
<textarea onKeyUp={this.handleKeyUp} value={this.state.value} ref="addComment"></textarea>
<button onClick={this.handleValidation}>submit</button>
</div>
)
}
})
var CommentList = React.createClass({
render: function() {
return (
<div>
{this.props.comments.map(function(comment){
return <CommentListElement key={comment.id} comment={comment} />;
})}
</div>
);
}
});
var CommentListElement = React.createClass({
render: function() {
return (
<div>{this.props.comment}</div>
)
}
})
React.render(<CommentSystem/>, document.getElementById('container'));
Hope this helps.

Autocomplete results will not be displayed inside asp.net mvc partial view

I have the following script that is rendered inside my _layout view:-
$(document).ready(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
and i added the following field to apply autocomplete on it:-
<input name="term" type="text" data-val="true"
data-val-required= "Please enter a value."
data-autocomplete-source= "#Url.Action("AutoComplete", "Staff")" />
now if i render the view as partial view then the script will not fire, and no autocomplete will be performed, so i added the autocomplete inside ajax-success as follow:-
$(document).ready(function () {
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
});
now after adding the AjaxSuccess the action method will be called, and when i check the response on IE F12 developers tools i can see that the browser will receive the json responce but nothing will be displayed inside the field (i mean the autocomplete results will not show on the partial view)?
EDIT
The action method which is responsible for the autocomplete is:-
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term).Select(a => new { label = a.SamAccUserName }).ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
EDIT2
here is the script which is responsible to show the modal popup:-
$(document).ready(function () {
$(function () {
$.ajaxSetup({ cache: false });
//$("a[data-modal]").on("click", function (e) {
$(document).on('click', 'a[data-modal]', function (e){
$('#myModalContent').css({ "max-height": screen.height * .82, "overflow-y": "auto" }).load(this.href, function () {
$('#myModal').modal({
//height: 1000,
//width: 1200,
//resizable: true,
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", "disabled");
$('#progress').show();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.ISsuccess) {
$('#myModal').modal('hide');
$('#progress').hide();
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
location.reload();
// alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
bindForm();
}
}
});
}
else {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
$('#progress').hide();
return false;
}
return false;
});
}
});
First, you don't need to wrap you ajaxSuccess fucntion in ready function.
Second, it's better to use POST when you get Json from server.
I tried to seproduce your problem, but have no luck.
Here how it works in my case(IE 11, MVC 4)
script on _Layout:
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: function (request, response) {
$.post(target.attr("data-autocomplete-source"), request, response);
},
minLength: 1,
delay: 1000
});
});
});
Controller method:
[HttpPost]
public JsonResult AutoComplete()
{
return Json(new List<string>()
{
"1",
"2",
"3"
});
}
Partial View html:
<input name="term" type="text" data-val="true"
data-val-required="Please enter a value."
data-autocomplete-source="#Url.Action("AutoComplete", "Stuff")" />
UPDATE:
I find out what your problem is. Jquery autocomplete needs array of objects that have lable and value properties. So if you change your controller code like this and it will work.
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term)
.Select(a => new { label = a.SamAccUserName, value = a.SamAccUserName })
.ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
Also you can do it on client side with $.map jquery function you can see example here

get instance of map in jquery ui map

i want to make the markers clustered with markerClusterer but i cannot get the map instance with jquery ui map . js
tried:
var map = $('#map_canvas').gmap('getMap');
or
var map = $('map_canvas').gmap('get', 'map');
and after:
var markerCluster = new MarkerClusterer(map, allMarkers);
but with errors
Thank you
Tried this . No Errors but no clusters...
$('#map_canvas').gmap({ 'callback': function () {
var self = this;
$.getJSON('Data/markers.json', function (data) {
$.each(data.markers, function (i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude,marker.longitude)}).click(function () {
$.ajax({
type: "GET",
url: "/LocoMap/LocoMap/InfoMobilePartialView/",
data: { latitude: marker.latitude, longitude: marker.longitude},
success: function (data) {
$("#marker-info").remove();
$(document.body).append("<div id='marker-info' data-role ='page'> </div>");
var $contentDiv = $("#marker-info");
$contentDiv.html(data).trigger('create');
$.mobile.changePage("#marker-info", { changeHash: false, type: "get", transition: 'pop',rel:"external" });
},
error: function (errorData) { onError(errorData); }
});
});
});
});
self.set('MarkerClusterer', new MarkerClusterer(this.get('map'), this.get('markers')));
}});
$('#map_canvas').gmap({'zoom': 2, 'disableDefaultUI':true}).bind('init', function(evt, map) {
$.getJSON( 'Data/markers.json', function(data) {
$.each( data.markers, function(i, m)
$('#map_canvas').gmap('addMarker', { 'position': new google.maps.LatLng(m.latitude, m.longitude), 'bounds':true } );
});
});
$('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map,$(this).gmap('get', 'markers')));
});
with no errors and no clusters
it seems **$(this).gmap('get', 'markers')));** returns Array[0]

Linked jQuery sortable lists and Backbone collections

I'm still finding my way with Backbone and I've always use Prototype instead of jQuery in the past so please forgive me if I'm doing something stupid.
I'm trying to develop a UI containing several connected unordered lists where each sortable list is represented by a separate Backbone collection. I'm using ICanHaz and Mustache templates but that's not of importance for my question.
When dragging items between the lists, how would I best achieve the automatic updating of the collections (remove a model from one and insert it into another)? I'm currently trying to use the receive and remove methods in the jQueryUI Sortable interaction — am I at least on the right lines?
var WS = {};
(function(ns) {
ns.Item = Backbone.Model.extend();
ns.Content = Backbone.Collection.extend({
model: ns.Item,
url: location.href,
initialize: function(el) {
this.el = $(el);
this.deferred = this.fetch();
},
recalculate: function() {
var count = this.length;
this.el.next(".subtotal").html(count);
},
setOrder: function() {
$.ajax({
url: this.url + "/reorder",
type: "POST",
data: "tasks=" + $(this.el).attr("id") + "&" + this.el.sortable("serialize")
});
}
});
ns.ContentRow = Backbone.View.extend({
tagName: "li",
className: "item",
events: {
"click .delete": "destroy"
},
initialize: function(options) {
_.bindAll(this, "render", "destroy");
this.model.bind("change", this.render);
this.model.view = this;
},
render: function() {
var row = ich.item(this.model.toJSON());
$(this.el).html(row);
return this;
},
destroy: function() {
if (confirm("Really delete?")) {
this.model.destroy({
success: function(model, response) {
$(model.view.el).remove();
},
error: function(model, response) {
console.log(response);
}
});
}
}
});
ns.ListView = Backbone.View.extend({
initialize: function(collection) {
this.el = collection.el;
this.collection = collection;
this.collection.bind("add", this.addOne, this);
_.bindAll(this, "addOne");
this.el.sortable({
axis: "y",
connectWith: ".tasks",
receive: _.bind(function(event, ui) {
// do something here?
}, this),
remove: _.bind(function(event, ui) {
// do something here?
}, this),
update: _.bind(function(event, ui) {
var list = ui.item.context.parentNode;
this.collection.setOrder();
}, this)
});
},
insert: function(item) {
var prefix = this.el.parentsUntil('ul').parent().attr("id"),
view = new ns.ContentRow({
model: item,
id: prefix + "_" + item.id
});
this.el.append(view.render().el);
},
addOne: function(item) {
if (item.isNew()) {
item.save({}, {
success: _.bind(function(model, response) {
// I should set id from JSON response when live
model.set({ id: this.collection.length });
this.insert(model);
}, this)
});
} else {
this.insert(item);
}
},
addAll: function() {
this.collection.each(this.addOne);
},
render: function() {
this.collection.deferred.done(_.bind(function() {
this.addAll();
}, this));
}
});
ns.AppView = Backbone.View.extend({
lists: [],
initialize: function(holder) {
holder.find("ul").each(_.bind(function(index, list) {
var Items = new WS.Content(list),
App = new WS.ListView(Items);
App.render();
this.lists.push(Items);
}, this));
}
});
})(WS);
$(document).ready(function() {
var App = new WS.AppView($("#tasks"));
});
You are on the right track. You will probably want to add the id of each sortable element into the template somewhere. Then when you receive the event, you know which model to add or remove from the collection. For example add...
<div data-id={{id}}> ... my thing ... </div>
And in the sortable call get the target's id attribute and call Collection.add() or remove()
Just use Backbone.CollectionView.. it has this functionality built in out of the box.
var listView = new Backbone.CollectionView( {
el : $( "#list1" ),
sortable : true,
sortableOptions : {
connectWith : "#list2"
},
collection : new Backbone.Collection
} );
var listView = new Backbone.CollectionView( {
el: $( "#list2" ),
sortable : true,
sortableOptions : {
connectWith : "#list1"
},
collection : new Backbone.Collection
} );

Resources