dart google-maps - triggering event - dart

I try to add a listener to my autocomplete box in order to select the first choice when pressing enter but it doesn't work.
event.addDomListener(input, 'keypress', (e) {
if (e.keyCode == 13) {
event.trigger(html.document.getElementById('pac-input').innerHtml, 'keydown',
html.KeyCode.DOWN);
}
});
I am not sure concerning
html.document.getElementById('pac-input').innerHtml
Thanks for your help.
[edit]
I use angular2.0.0-beta.21.
My template is :
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="map-canvas" style="height: 500px;"></div>
and my component :
#Component(
selector: 'myComponent',
templateUrl: 'template.html',
pipes: const [IntlPipe]
)
class MyComponent implements OnInit {
final UserService _userService;
final IntlService _intlService;
Autocomplete autocomplete;
GMap map;
String infoMessage = "";
String errorMessage = "";
CornersComponent(this._userService, this._intlService);
#override
ngOnInit() {
var mapOptions = new MapOptions()
..zoom = 13
..maxZoom = 19
..minZoom = 12
..center = new LatLng(48.871083, 2.346348)
..mapTypeId = MapTypeId.ROADMAP
..streetViewControl = false
..panControl = false
..mapTypeControl = false
..scrollwheel = false
..styles = <MapTypeStyle>[
new MapTypeStyle()
..featureType = MapTypeStyleFeatureType.POI_BUSINESS
..elementType = MapTypeStyleElementType.LABELS
..stylers = <MapTypeStyler>[
new MapTypeStyler()
..visibility = 'off'
]
];
map = new GMap(html.querySelector("#map-canvas"), mapOptions);
var input = html.document.getElementById('pac-input') as html
.InputElement;
map.controls[ControlPosition.TOP_LEFT].push(input);
autocomplete = new Autocomplete(input);
autocomplete.bindTo('bounds', map);
final infowindow = new InfoWindow();
final marker = new Marker(new MarkerOptions()
..map = map
..anchorPoint = new Point(0, -29));
autocomplete.onPlaceChanged.listen((_) {
infowindow.close();
marker.visible = false;
final place = autocomplete.place;
if (place.geometry == null) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport != null) {
map.fitBounds(place.geometry.viewport);
} else {
map.center = place.geometry.location;
map.zoom = 15; // Why 17? Because it looks good.
}
marker.icon = new Icon()
..url = place.icon
..size = new Size(71, 71)
..origin = new Point(0, 0)
..anchor = new Point(17, 34)
..scaledSize = new Size(35, 35);
marker.position = place.geometry.location;
marker.visible = true;
String address = '';
if (place.addressComponents != null) {
address = [
(place.addressComponents[0] != null &&
place.addressComponents[0].shortName != null
? place.addressComponents[0].shortName
: ''),
(place.addressComponents[1] != null &&
place.addressComponents[1].shortName != null
? place.addressComponents[1].shortName
: ''),
(place.addressComponents[2] != null &&
place.addressComponents[2].shortName != null
? place.addressComponents[2].shortName
: '')
].join(' ');
}
infowindow.content = '<div><strong>${place.name}</strong><br>${address}';
infowindow.open(map, marker);
});
event.addDomListener(input, 'keypress', (e) {
assert(e is html.KeyboardEvent);
if (e.keyCode == html.KeyCode.ENTER) {
event.trigger(input, 'keydown',
new html.KeyEvent('keydown', keyCode: html.KeyCode.DOWN));
}
});
}
}
I have found a workaround :
Calling at the end on the ngOnInit method :
context.callMethod('myJavascriptMethod');
function myJavascriptMethod() {
var input = document.getElementById('pac-input');
google.maps.event.addDomListener(input, 'keypress', function (e) {
if (e.keyCode === 13) {
google.maps.event.trigger(this, 'keydown', {"keyCode": 40});
}
});
}

The following code should work:
import 'dart:js_util' show jsify;
event.addDomListener(input, 'keypress', (e) {
assert(e is html.KeyboardEvent);
if (e.keyCode == html.KeyCode.ENTER) {
event.trigger(input, 'keydown', jsify({'keyCode': html.KeyCode.DOWN}));
}
});
You can alternatively use the following to trigger events:
input.dispatchEvent(new html.KeyEvent('keydown', keyCode: html.KeyCode.DOWN));

Related

Flash of previous page while navigating between pages in react js application

I am developing a react js application for ios and android. In my application while navigating from one page to another,a flash of previous page is displaying for 1 second and then my next page is loading.This issue is prevalent only in ios app.
Issue does not appear while checking in browser safari,chrome.Only in app
Please provide solution.
We are not using react native and react router.
Few pages are developed in reactjs and integrated in to an existing mobile app.
In the above code:
else {
console.log('clicked');
window.location.href = path + '?id=' + id + '&time=' `window.sessionStorage.getItem('time') + '&prodId=' + productId + '&qty=' + `qty + '&storeCall=true';
}
here we are navigating to another jsx page with window.location.href
While navigating a getting issues in ios app.Flash of previous page showing up for a second
import React from 'react';
import Copyright from './Copyright.jsx';
import { browserHistory } from 'react-router';
import axios from 'axios';
import envConstant from '../../../../../config/labelConstants.js';
import { ClipLoader } from 'react-spinners';
var x=0;
let submitOrder, flag = "false", footerBtn = '', vendor;
let closeFunc;
class Footer extends React.Component {
constructor(props) {
super(props);
this.orderSubmit = this.orderSubmit.bind(this);
this.validateSubmit = this.validateSubmit.bind(this);
this.validateNetwork = this.validateNetwork.bind(this);
this.disableBtn = this.disableBtn.bind(this);
this.state = {
data: 'Initial data....',
price: 'total',
loading:false
}
this.propTypes = {
alertFunc: React.PropTypes.func,
couponAvail: React.PropTypes.func,
alertClose:React.PropTypes.func
};
};
validateSubmit() {
const react = this;
var submit = false;
var phoneNum;
var fname = this.props.UserDetails.refs.fname.value;
var lname = this.props.UserDetails.refs.lname.value;
var phone = this.props.UserDetails.refs.phone.value.replace(/[-.]/gi, '');
if (phone != null) {
phoneNum = phone.toString();
}
var email = this.props.UserDetails.refs.email.value;
var agree = window.sessionStorage.getItem('agree');
submitOrder = {};
let prodId, qty;
if (null == window.sessionStorage.getItem('prodID') && null == window.sessionStorage.getItem('qty')) {
prodId = window.sessionStorage.getItem('initprodID');
qty = 1;
} else {
prodId = window.sessionStorage.getItem('prodID');
qty = window.sessionStorage.getItem('qty');
}
submitOrder = {
fname: this.props.UserDetails.refs.fname.value,
lname: this.props.UserDetails.refs.lname.value,
coupon: window.sessionStorage.getItem('successCoupon'),
email: this.props.UserDetails.refs.email.value,
phoneNum: this.props.UserDetails.refs.phone.value.replace(/[-.]/gi, ''),
id: window.sessionStorage.getItem('id'),
qty: qty,
prodID: prodId,
emailOptIn: window.sessionStorage.getItem('emailOptIn'),
smsOptIn: window.sessionStorage.getItem('smsOptIn'),
time: window.sessionStorage.getItem('time')
};
if (fname == null || fname == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.fname);
submit = false;
return false;
}
if (lname == null || lname == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.lname);
submit = false;
return false;
}
if (phoneNum == null || phoneNum == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.phone);
submit = false;
return false;
}
if (email == null || email == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.email);
submit = false;
return false;
}
if ('' != fname || null != fname || '' == lname || null != lname) {
submit = true;
}
if (null != fname || '' != fname) {
const re = /^[a-zA-Z\ ]*$/;
if (!re.test(fname)) {
this.props.alertFunc(envConstant.invalidName,react.props.UserDetails.refs.fname);
submit = false;
return false;
} else {
submit = true;
}
}
if (null != lname || '' != lname) {
const re = /^[a-zA-Z\'\-\. ]*$/;
if (!re.test(lname)) {
this.props.alertFunc(envConstant.invalidName,react.props.UserDetails.refs.lname);
submit = false;
return false;
} else {
submit = true;
}
}
if (null != phoneNum || '' != phoneNum) {
if (vendor == "boots") {
if (phoneNum.length != "11") {
this.props.alertFunc(envConstant.invalidPhnum,react.props.UserDetails.refs.phone);
submit = false;
return false;
} else {
submit = true;
}
} else if (vendor == "roi") {
const re = /^[0]+[0-9]*$/;
if (phoneNum.length != "11" || !re.test(phoneNum)) {
this.props.alertFunc(envConstant.invalidPhnum,react.props.UserDetails.refs.phone);
submit = false;
return false;
} else {
submit = true;
}
} else {
if (phoneNum.length != "10") {
this.props.alertFunc(envConstant.invalidPhnum,react.props.UserDetails.refs.phone);
submit = false;
return false;
} else {
submit = true;
}
}
}
if (null != email || '' != email) {
const re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!re.test(email)) {
this.props.alertFunc(envConstant.invalidEmail,react.props.UserDetails.refs.email);
submit = false;
return false;
} else {
submit = true;
}
}
if (agree == "false" || null == agree) {
this.props.alertFunc(envConstant.agreeTerms);
submit = false;
return false;
}
if (submit == true) {
return true;
}
}
validateNetwork() {
var hasConn = window.navigator.onLine;
if (hasConn) {
return hasConn;
}
else {
this.props.alertFunc(envConstant.networkFailure);
}
}
orderSubmit(e) {
const react = this;
if (this.props.footer == envConstant.submitFoot) {
window.sessionStorage.setItem('id', this.props.id);
if (this.validateNetwork()) {
if (this.validateSubmit()) {
axios({
method: 'post',
url: react.props.urlValue + '/inputFields',
data: submitOrder
}).then((response) => {
this.setState({loading:true});
window.location.href = react.props.path;
});
}
}
}
if (this.props.footer == envConstant.orderInfoFoot) {
if (this.validateNetwork()) {
let qty, productId;
this.setState({loading:true});
if (null == window.sessionStorage.getItem('qty') || 'null' == `window.sessionStorage.getItem('qty')) {`
qty = 1;
productId = window.sessionStorage.getItem('initprodID');
} else {
qty = window.sessionStorage.getItem('qty');
productId = window.sessionStorage.getItem('prodID');
}
let path = this.props.path;
let id = this.props.id;
if (null != window.sessionStorage.getItem('coupon') && "null" != `window.sessionStorage.getItem('coupon')) {`
if (window.sessionStorage.getItem('errorcode') == '' && null != `window.sessionStorage.getItem('coupon') &&` `window.sessionStorage.getItem('couponApplied') == "true") {`
setTimeout(function () {
if (window.sessionStorage.getItem('status1') != 'failure') {
window.location.href = path + '?id=' + id + '&time=' + `window.sessionStorage.getItem('time') + '&prodId=' + productId + '&qty=' +` `qty + '&storeCall=true';`
}
},1500);
}
}
else {
console.log('clicked');
window.location.href = path + '?id=' + id + '&time=' + `window.sessionStorage.getItem('time') + '&prodId=' + productId + '&qty=' +` `qty + '&storeCall=true';`
}
}
}
if (this.props.footer == envConstant.ThankyouFoot) {
let callBackUrl = this.props.callBackUrl;
if (window.navigator.userAgent.includes("iPhone")) {
window.location = "QP_DONE:DONE";
} else {
try {
window.quickprint.onCheckoutComplete();
} catch (e) {
if (undefined != callBackUrl && '' != callBackUrl && null != callBackUrl) {
if (callBackUrl.includes('?')) {
window.location = callBackUrl + '?action=done';
} else {
window.location = callBackUrl + '&action=done';
}
}
}
}
}
}
componentDidMount() {
let footerHeight = this.refs.footerHeight.clientHeight;
window.sessionStorage.setItem('footerHeight', footerHeight);
}
disableBtn(id) {
window.sessionStorage.setItem('disable', "true");
if(window.sessionStorage.getItem('alert1'+id)=="0" || `window.sessionStorage.getItem('alert1'+id)=="1" || `window.sessionStorage.getItem('alert1'+id)==1){
alert(envConstant.priceInvalid);
}else{
x=0;
window.sessionStorage.setItem('alert1'+id,x++);
}
//this.props.alertFunc(envConstant.priceInvalid)
}
render() {
vendor = this.props.vendor;
let copyrightsWrapper;
if (vendor != "ts" && vendor != "roi") {
copyrightsWrapper = (
<Copyright copyRightMessage={this.props.copyRightMessage} />
);
}
if (typeof window !== 'undefined') {
window.sessionStorage.setItem('callBackUrl',this.props.callBackUrl);
if (window.sessionStorage.getItem('status') == "success" || `window.sessionStorage.getItem('status') == "") {`
if ((window.sessionStorage.getItem('status1') != "failure" || `window.sessionStorage.getItem('couponApplied') == "false") && `window.sessionStorage.getItem('flagDrop') != "true" &&` `window.sessionStorage.getItem('couponFocus') != "true") {
var discTotal = `window.sessionStorage.getItem('discount').split(this.props.currency);`
if (parseInt(discTotal[1]) > 998) {
window.sessionStorage.setItem('alert1'+this.props.id,x++);
this.disableBtn(this.props.id);
} else {
window.sessionStorage.setItem('disable', "false");
}
}
}
if (window.sessionStorage.getItem('status') == null) {
if (window.sessionStorage.getItem('invalid') != 'true') {
if (null == window.sessionStorage.getItem('total')) {
var initTotal = `window.sessionStorage.getItem('inittotal').split(this.props.currency);`
if (parseInt(initTotal[1]) > 998) {
window.sessionStorage.setItem('alert1'+this.props.id,1);
this.disableBtn(this.props.id);
} else {
window.sessionStorage.setItem('disable', "false");
}
} else {
var prodTotal = `window.sessionStorage.getItem('total').split(this.props.currency);`
if (parseInt(prodTotal[1]) > 998) {
window.sessionStorage.setItem('alert1'+this.props.id,1);
this.disableBtn(this.props.id);
} else {
window.sessionStorage.setItem('disable', "false");
}
}
}
}
if (window.sessionStorage.getItem('disable') == "true") {
footerBtn = (
<button type="button"
className="btn-off supp-color btn-w1" `disabled="disabled"> {this.props.footer}</button>`
);
} else {
footerBtn = (
<button ref="footerBtn" type="button" className="btn-on supp-color btn-`w1" onClick={this.orderSubmit}>{this.props.footer}</button>`
);
}
}else{
footerBtn = (
<button ref="footerBtn" type="button" className="btn-on supp-color btn-w1" >{this.props.footer}</button>
);
}
return (
<div className="op-footer footer_height" ref="footerHeight" id="footerValue">
{copyrightsWrapper}
<div className="background-white">
<div className={'sweet-loading '+ this.state.loading}>
<ClipLoader color={'#a0a0a0'} loading={this.state.loading}/>
</div>
{footerBtn}
</div>
</div>
);
}
}
export default Footer;

How to insert to latitude and longitude in database

I am developing a mvc5 web application. I am trying to store the user's location (Latitude, Longitude) to a database. I can save the location name. But, i can't save latitude and longitude info. How can i insert these?
Thanks for your help.
listing.Cshtml file:
<fieldset>
<legend>[[[Location]]]</legend>
<div class="form-group">
<label>[[[Location]]]</label>
<input type="text" class="form-control input-lg" placeholder="[[[Enter Location]]]" id="Location" name="Location" value="#Model.ListingItem.Location">
</div>
<input type="hidden" id="Longitude" name="Longitude" value="#Model.ListingItem.Longitude" />
<input type="hidden" id="Latitude" name="Latitude" value="#Model.ListingItem.Latitude" />
<div class="form-group">
<div id="map-canvas"></div>
</div>
</fieldset>
listingController:
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable<HttpPostedFileBase> files)
{
if (CacheHelper.Categories.Count == 0)
{
TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
TempData[TempDataKeys.UserMessage] = "[[[There are not categories available yet.]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
var userIdCurrent = User.Identity.GetUserId();
// Register account if not login
if (!User.Identity.IsAuthenticated)
{
var accountController = BeYourMarket.Core.ContainerManager.GetConfiguredContainer().Resolve<AccountController>();
var modelRegister = new RegisterViewModel()
{
Email = listing.ContactEmail,
Password = form["Password"],
ConfirmPassword = form["ConfirmPassword"],
};
// Parse first and last name
var names = listing.ContactName.Split(' ');
if (names.Length == 1)
{
modelRegister.FirstName = names[0];
}
else if (names.Length == 2)
{
modelRegister.FirstName = names[0];
modelRegister.LastName = names[1];
}
else if (names.Length > 2)
{
modelRegister.FirstName = names[0];
modelRegister.LastName = listing.ContactName.Substring(listing.ContactName.IndexOf(" ") + 1);
}
// Register account
var resultRegister = await accountController.RegisterAccount(modelRegister);
// Add errors
AddErrors(resultRegister);
// Show errors if not succeed
if (!resultRegister.Succeeded)
{
var model = new ListingUpdateModel()
{
ListingItem = listing
};
// Populate model with listing
await PopulateListingUpdateModel(listing, model);
return View("ListingUpdate", model);
}
// update current user id
var user = await UserManager.FindByNameAsync(listing.ContactEmail);
userIdCurrent = user.Id;
}
bool updateCount = false;
int nextPictureOrderId = 0;
// Set default listing type ID
if (listing.ListingTypeID == 0)
{
var listingTypes = CacheHelper.ListingTypes.Where(x => x.CategoryListingTypes.Any(y => y.CategoryID == listing.CategoryID));
if (listingTypes == null)
{
TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
TempData[TempDataKeys.UserMessage] = "[[[There are not listing types available yet.]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
listing.ListingTypeID = listingTypes.FirstOrDefault().ID;
}
if (listing.ID == 0)
{
listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
listing.IP = Request.GetVisitorIP();
listing.Expiration = DateTime.MaxValue.AddDays(-1);
listing.UserID = userIdCurrent;
listing.Enabled = true;
listing.Currency = CacheHelper.Settings.Currency;
updateCount = true;
_listingService.Insert(listing);
}
else
{
if (await NotMeListing(listing.ID))
return new HttpUnauthorizedResult();
var listingExisting = await _listingService.FindAsync(listing.ID);
listingExisting.Title = listing.Title;
listingExisting.Description = listing.Description;
listingExisting.Tags = listing.Tags;
listingExisting.Active = listing.Active;
listingExisting.Price = listing.Price;
listingExisting.ContactEmail = listing.ContactEmail;
listingExisting.ContactName = listing.ContactName;
listingExisting.ContactPhone = listing.ContactPhone;
listingExisting.Latitude = listing.Latitude;
listingExisting.Longitude = listing.Longitude;
listingExisting.Location = listing.Location;
listingExisting.ShowPhone = listing.ShowPhone;
listingExisting.ShowEmail = listing.ShowEmail;
listingExisting.CategoryID = listing.CategoryID;
listingExisting.ListingTypeID = listing.ListingTypeID;
listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
_listingService.Update(listingExisting);
}
// Delete existing fields on item
var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();
var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();
foreach (var customFieldId in customFieldIds)
{
await _customFieldListingService.DeleteAsync(customFieldId);
}
// Get custom fields
var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();
var customFieldCategories = customFieldCategoryQuery.ToList();
foreach (var metaCategory in customFieldCategories)
{
var field = metaCategory.MetaField;
var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;
string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);
var formValue = form[controlId];
if (string.IsNullOrEmpty(formValue))
continue;
formValue = formValue.ToString();
var itemMeta = new ListingMeta()
{
ListingID = listing.ID,
Value = formValue,
FieldID = field.ID,
ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
};
_customFieldListingService.Insert(itemMeta);
}
await _unitOfWorkAsync.SaveChangesAsync();
if (Request.Files.Count > 0)
{
var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
if (itemPictureQuery.Count() > 0)
nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
}
if (files != null && files.Count() > 0)
{
foreach (HttpPostedFileBase file in files)
{
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
// Picture picture and get id
var picture = new Picture();
picture.MimeType = "image/jpeg";
_pictureService.Insert(picture);
await _unitOfWorkAsync.SaveChangesAsync();
// Format is automatically detected though can be changed.
ISupportedImageFormat format = new JpegFormat { Quality = 90 };
Size size = new Size(500, 0);
//https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
// Initialize the ImageFactory using the overload to preserve EXIF metadata.
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
{
var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));
// Load, resize, set the format and quality and save an image.
imageFactory.Load(file.InputStream)
.Resize(size)
.Format(format)
.Save(path);
}
var itemPicture = new ListingPicture();
itemPicture.ListingID = listing.ID;
itemPicture.PictureID = picture.ID;
itemPicture.Ordering = nextPictureOrderId;
_listingPictureservice.Insert(itemPicture);
nextPictureOrderId++;
}
}
}
await _unitOfWorkAsync.SaveChangesAsync();
// Update statistics count
if (updateCount)
{
_sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
_dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
}
TempData[TempDataKeys.UserMessage] = "[[[Listing is updated!]]]";
return RedirectToAction("Listing", new { id = listing.ID });
}
My page screenshot:
enter image description here
Consequently, i can insert location in my db. But, i can't latitude and longitude insert.
How can i solve this problem?
initmap function:
function initMap() {
var isDraggable = $(document).width() > 480 ? true : false; // If document (your website) is wider than 480px, isDraggable = true, else isDraggable = false
var mapOptions = {
draggable: isDraggable,
scrollwheel: false, // Prevent users to start zooming the map when scrolling down the page
zoom: 7,
center: new google.maps.LatLng(39.8688, 32.2195),
};
#{ var hasLatLng = #Model.ListingItem.Latitude.HasValue && #Model.ListingItem.Longitude.HasValue; }
var hasLatLng = #hasLatLng.ToString().ToLowerInvariant();
#if (hasLatLng){
<text>
mapOptions = {
center: new google.maps.LatLng(#Model.ListingItem.Latitude.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), #Model.ListingItem.Longitude.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)),
zoom: 7
};
</text>
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
#if (hasLatLng){
<text>
var marker = new google.maps.Marker({
position: new google.maps.LatLng(#Model.ListingItem.Latitude, #Model.ListingItem.Longitude),
map: map
});
marker.setVisible(true);
</text>
}
geocoder = new google.maps.Geocoder();
var input = (document.getElementById('Location'));
// Try HTML5 geolocation
if (#Model.ListingItem.ID == 0){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
geocoder.geocode({ 'latLng': pos }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(14);
map.setCenter(pos);
marker = new google.maps.Marker({
position: pos,
map: map,
content: results[1].formatted_address
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
$('#Location').val(results[1].formatted_address);
$('#Latitude').val(pos.lat());
$('#Longitude').val(pos.lng());
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// Set lat/long
$('#Latitude').val(place.geometry.location.lat());
$('#Longitude').val(place.geometry.location.lng());
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(12);
}
marker.setIcon(({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
google.maps.event.addDomListener(input, 'keydown', function (e) {
if (e.keyCode == 13) {
if (e.preventDefault) {
e.preventDefault();
}
else {
// Since the google event handler framework does not handle
e.cancelBubble = true;
e.returnValue = false;
}
}
});
}
save button:
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> [[[Save]]]</button>
<i class="fa fa-remove"></i> [[[Cancel]]]
</div>
</div>

.Net RunTimeBinderException

I have a data content witch contains complex data I just need index names which seem in Dynamic View in data. In debug mode I can see the datas but cant get them..
You can see the contents of data in image below):
if(hits.Count() > 0)
{
var data = hits.FirstOrDefault().Source;
var dataaa = JsonConvert.DeserializeObject(hits.FirstOrDefault().Source);
}
I found a solution with checking if selected index has documents; if yes,
I take the first document in index, and parse it to keys(field names) in client.
here is my func:
[HttpPost]
public ActionResult getIndexFields(string index_name)
{
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(
node,
defaultIndex: index_name
);
var esclient = new ElasticClient(settings);
var Documents = esclient.Search<dynamic>(s => s.Index(index_name).AllTypes().Source());
string fields = "";
if (Documents.Documents.Count() > 0)
{
fields = JsonConvert.SerializeObject(Documents.Documents.FirstOrDefault());
var data = Documents.Documents.FirstOrDefault().Source;
return Json(new
{
result = fields,
Success = true
});
}
return Json(new
{
result = "",
Success = false
});
}
and my js:
$.ajax({
url: "getIndexFields?index_name=" + $(this).val(),
type: "POST",
success: function (data) {
if (data.Success) {
var fields = JSON.parse(data.result);
var fields_arr = [];
$.each(fields, function (value, index) {
fields_arr.push(
{
id: value,
label: value
})
});
options.filters = fields_arr;
var lang = "en";//$(this).val();
var done = function () {
var rules = $b.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
options.rules = rules;
}
options.lang_code = lang;
$b.queryBuilder('destroy');
$('#builder').queryBuilder(options);
};
debugger
if ($.fn.queryBuilder.regional[lang] === undefined) {
$.getScript('../dist/i18n/query-builder.' + lang + '.js', done);
}
else {
done();
}
}
else {
event.theme = 'ruby';
event.heading = '<i class=\'fa fa-warning\'></i> Process Failure';
event.message = 'User could not create.';
event.sticky = true;
$("#divfailed").empty();
$("#divfailed").hide();
$("#divfailed").append("<i class='fa fa-warning'></i> " + data.ErrorMessage);
$("#divfailed").show(500);
setTimeout(function () {
$("#divfailed").hide(500);
}, 3000);
}
},
error: function (a, b, c) {
debugger
event.theme = 'ruby';
event.heading = '<i class=\'fa fa-warning\'></i> Process Failure';
event.message = 'Object could not create.';
$("#divfailed").empty();
$("#divfailed").hide();
msg = c !== "" ? c : a.responseText;
$("#divfailed").append("<i class='fa fa-warning'></i> " + msg);
$("#divfailed").show(500);
setTimeout(function () {
$("#divfailed").hide(500);
}, 3000);
}
});

Local storage not working with drop down menu

I have a problem with saving data to storage.
I am using text fields and drop down menus.
Text field are working fine with saving but dropdown menu ain't working.
As you can see i am using local storage from html 5 to save everything
Does anyone know what the problem is ?
Woonplaats and favomuziek are with dropdown menu
$(document).ready(function(){
if (!window.localStorage){
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var result = ""
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0){
result = c.substring(nameEQ.length,c.length);
}else{
result = "";
}
}
return(result);
}
localStorage = (function () {
return {
setItem: function (key, value) {
createCookie(key, value, 3000)
},
getItem: function (key) {
return(readCookie(key));
}
};
})();
}
load_settings();
$('#gebruikersprofiel').submit(function(event){
event.preventDefault();
save_settings();
});
});
function save_settings(){
localStorage.setItem("voornaam", $("#voornaam").val());
localStorage.setItem("achternaam", $("#achternaam").val());
localStorage.setItem("woonplaats", $("#woonplaats").val());
localStorage.setItem("favomuziek", $("#favomuziek").val());
apply_preferences_to_page();
}
function apply_preferences_to_page(){
$("body").css("voornaam", $("#voornaam").val());
$("body").css("achternaam", $("#achternaam").val());
$("body").css("woonplaats", $("#woonplaats").val() );
$("body").css("favomuziek", $("#favomuziek").val() );
}
$(document).ready(function(){
if (!window.localStorage){
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var result = ""
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0){
result = c.substring(nameEQ.length,c.length);
}else{
result = "";
}
}
return(result);
}
localStorage = (function () {
return {
setItem: function (key, value) {
createCookie(key, value, 3000)
},
getItem: function (key) {
return(readCookie(key));
}
};
})();
}
load_settings();
$('#gebruikersprofiel').submit(function(event){
event.preventDefault();
save_settings();
});
});
function save_settings(){
localStorage.setItem("voornaam", $("#voornaam").val());
localStorage.setItem("achternaam", $("#achternaam").val());
localStorage.setItem("woonplaats", $("#woonplaats").val());
localStorage.setItem("favomuziek", $("#favomuziek").val());
apply_preferences_to_page();
}
function apply_preferences_to_page(){
$("body").css("voornaam", $("#voornaam").val());
$("body").css("achternaam", $("#achternaam").val());
$("body").css("woonplaats", $("#woonplaats").val() );
$("body").css("favomuziek", $("#favomuziek").val() );
}

How to read modelstate errors when returned by Json?

How can I display ModelState errors returned by JSON?
I want to do something like this:
if (!ValidateLogOn(Name, currentPassword))
{
ModelState.AddModelError("_FORM", "Username or password is incorrect.");
//Return a json object to the javascript
return Json(new { ModelState });
}
What must be my code in the view to read the ModelState errors and display them?
My actual code in the view to read the JSON values is as follows:
function createCategoryComplete(e) {
var obj = e.get_object();
alert(obj.Values);
}
This is draft code but the same idea works for me in production.
The main idea here is that Json errors have predefined tag names, that no normal objects will have. For errors validation errors HTML is re-created using JavaScript (both top summary and form elements highlighting).
Server side:
public static JsonResult JsonValidation(this ModelStateDictionary state)
{
return new JsonResult
{
Data = new
{
Tag = "ValidationError",
State = from e in state
where e.Value.Errors.Count > 0
select new
{
Name = e.Key,
Errors = e.Value.Errors.Select(x => x.ErrorMessage)
.Concat(e.Value.Errors.Where(x => x.Exception != null).Select(x => x.Exception.Message))
}
}
};
}
in action:
if (!ModelState.IsValid && Request.IsAjaxRequest())
return ModelState.JsonValidation();
Client side:
function getValidationSummary() {
var el = $(".validation-summary-errors");
if (el.length == 0) {
$(".title-separator").after("<div><ul class='validation-summary-errors ui-state-error'></ul></div>");
el = $(".validation-summary-errors");
}
return el;
}
function getResponseValidationObject(response) {
if (response && response.Tag && response.Tag == "ValidationError")
return response;
return null;
}
function CheckValidationErrorResponse(response, form, summaryElement) {
var data = getResponseValidationObject(response);
if (!data) return;
var list = summaryElement || getValidationSummary();
list.html('');
$.each(data.State, function(i, item) {
list.append("<li>" + item.Errors.join("</li><li>") + "</li>");
if (form && item.Name.length > 0)
$(form).find("*[name='" + item.Name + "']").addClass("ui-state-error");
});
}
$.ajax(... function(response) {
CheckValidationErrorResponse(xhr.responseText); } );
Why not return the original ModelState object to the client, and then use jQuery to read the values. To me it looks much simpler, and uses the common data structure (.net's ModelState)
C#:
return Json(ModelState);
js:
var message = "";
if (e.response.length > 0) {
$.each(e.response, function(i, fieldItem) {
$.each(fieldItem.Value.Errors, function(j, errItem) {
message += errItem.ErrorMessage;
});
message += "\n";
});
alert(message);
}
this is a tiny tweak to queen3's client side code which handles specific validation messages, and creates a similar document to that created by MVC3:
function getValidationSummary() {
var $el = $(".validation-summary-errors > ul");
if ($el.length == 0) {
$el = $("<div class='validation-summary-errors'><ul></ul></div>")
.hide()
.insertBefore('fieldset:first')
.find('ul');
}
return $el;
}
function getResponseValidationObject(response) {
if (response && response.Tag && response.Tag == "ValidationError")
return response;
return null;
}
function isValidationErrorResponse(response, form, summaryElement) {
var $list,
data = getResponseValidationObject(response);
if (!data) return false;
$list = summaryElement || getValidationSummary();
$list.html('');
$.each(data.State, function (i, item) {
var $val, lblTxt, errorList ="";
if (item.Name) {
$val = $(".field-validation-valid,.field-validation-error")
.first("[data-valmsg-for=" + item.Name + "]")
.removeClass("field-validation-valid")
.addClass("field-validation-error");
$("input[name=" + item.Name + "]").addClass("input-validation-error")
lblTxt = $("label[for=" + item.Name + "]").text();
if (lblTxt) { lblTxt += ": "; }
}
if ($val.length) {
$val.text(item.Errors.shift());
if (!item.Errors.length) { return; }
}
$.each(item.Errors, function (c,val) {
errorList += "<li>" + lblTxt + val + "</li>";
});
$list.append(errorList);
});
if ($list.find("li:first").length) {$list.closest("div").show(); }
return true;
}
See below for code with a few amendments to Brent's answer. CheckValidationErrorResponse looks for the Validation Summary regardless of whether it's in the valid or invalid state, and inserts it if not found. If validation errors are found in the response, it applies the validation-summary-errors class to the Summary, else it applies validation-summary-valid. It assumes CSS is present to control the visibility of the Summary.
The code clears existing instances of field-validation-error, and reapplies them for errors found in the response.
function getValidationSummary(form) {
var $summ = $(form).find('*[data-valmsg-summary="true"]');
if ($summ.length == 0)
{
$summ = $('<div class="validation-summary-valid" data-valmsg-summary="true"><ul></ul></div>');
$summ.appendTo(form);
}
return $summ;
}
function getValidationList(summary) {
var $list = $(summary).children('ul');
if ($list.length == 0) {
$list = $('<ul></ul>');
$list.appendTo(summary);
}
return $list;
}
function getResponseValidationErrors(data) {
if (data && data.ModelErrors && data.ModelErrors.length > 0)
return data.ModelErrors;
return null;
}
function CheckValidationErrorResponse(data, form, summaryElement) {
var errors = getResponseValidationErrors(data);
var $summ = summaryElement || getValidationSummary(form);
var $list = getValidationList($summ);
$list.html('');
$(form).find(".field-validation-error")
.removeClass("field-validation-error")
.addClass("field-validation-valid");
if (!errors)
{
$summ.removeClass('validation-summary-errors').addClass('validation-summary-valid');
return false;
}
$.each(errors, function (i, item) {
var $val, $input, errorList = "";
if (item.Name) {
$val = $(form).find(".field-validation-valid, .field-validation-error")
.filter("[data-valmsg-for=" + item.Name + "]")
.removeClass("field-validation-valid")
.addClass("field-validation-error");
$input = $(form).find("*[name='" + item.Name + "']");
if (!$input.is(":hidden") && !$val.length)
{
$input.parent().append("<span class='field-validation-error' data-valmsg-for='" + item.Name + "' data-valmsg-replace='false'>*</span>");
}
$input.addClass("input-validation-error");
}
$.each(item.Errors, function (c, err) {
errorList += "<li>" + err + "</li>";
});
$list.append(errorList);
});
$summ.removeClass('validation-summary-valid').addClass('validation-summary-errors');
return true;
}
C#
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
JavaScript
$.ajax({
type: "GET",
url: "/api/xxxxx",
async: 'false',
error: function (xhr, status, err) {
if (xhr.status == 400) {
DisplayModelStateErrors(xhr.responseJSON.ModelState);
}
},
....
function DisplayModelStateErrors(modelState) {
var message = "";
var propStrings = Object.keys(modelState);
$.each(propStrings, function (i, propString) {
var propErrors = modelState[propString];
$.each(propErrors, function (j, propError) {
message += propError;
});
message += "\n";
});
alert(message);
};
If you are returning JSON, you cannot use ModelState. Everything that the view needs should be contained inside the JSON string. So instead of adding the error to the ModelState you could add it to the model you are serializing:
public ActionResult Index()
{
return Json(new
{
errorControl = "_FORM",
errorMessage = "Username or password is incorrect.",
someOtherProperty = "some other value"
});
}

Resources