My View :-
<form class="commentform commentright" enctype="multipart/form-data" >
<textarea class="simpleta required" name="Body" placeholder="Discuss this vehicle with other members of Row52."></textarea>
<input type="file" id="fileuploadfield" name="fileuploadfield"/>
<input type="submit" value="Submit" class="btn btn-inverse btn-small"/>
<input type="hidden" name="ParentId" value="0"/>
<input type="hidden" name="VehicleId" value="#Model.VehicleId"/>
<span class="commentcount"><span class="numberofcomments">#Model.Count</span>#count</span>
<div class="feedback"></div>
<img id="img" src="" />
</form>
JQuery :-
submitComment: function (form, type) {
var self = this;
var $this = $(form);
var formData = $this.serialize();
var $message = $this.find('.feedback');
$message.hide();
$message.html('');
var val = validation({ $form: $this });
if (val.checkRequired()) {
$this.indicator({ autoStart: false, minDuration: 100 });
$this.indicator('start');
var files = $("#fileuploadfield").get(0).files;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
}
else {
alert("This browser doesn't support HTML5 multiple file uploads!");
}
}
else {
alert("This");
}
$.ajax('/api/v2/comment/Post/', {
type: 'POST',
contentType: 'multipart/form-data',
// I have also use contentType: false,
processData: false,
data: formData
}).done(function (d) {
Controller :-
public Task<HttpResponseMessage> Post()
{
var provider = new MultipartMemoryStreamProvider();
var task1 = Request.Content.ReadAsMultipartAsync(provider);
var userId = User.Id;
return task1.Then(providerResult =>
{
var file = GetFileContent(providerResult);
var task2 = file.ReadAsStreamAsync();
string originalFileName = file.Headers.ContentDisposition.FileName.Replace("\"", "");
string extension = Path.GetExtension(originalFileName);
string fileName = Guid.NewGuid().ToString() + extension;
return task2.Then(stream =>
{
if (stream.Length > 0)
{
var kernel = WindsorContainerFactory.Create(KernelState.Thread, ConfigurationState.Web);
CloudBlobContainer container = GetContainer();
var userRepo = kernel.Resolve<IUserRepository>();
var logger = kernel.Resolve<ILogger>();
logger.Fatal("Original File Name: " + originalFileName);
logger.Fatal("Extension: " + extension);
logger.Fatal("File Name: " + fileName);
var user = userRepo.FirstOrDefault(x => x.Id == userId);
var path = CreateImageSize(stream, 500, fileName, userId, container, logger);
if (user != null)
{
user.AvatarOriginalFileName = fileName;
user.AvatarOriginalAbsolutePath =
ConfigurationManager.AppSettings["CdnUserEndpointUrl"] + path;
user.AvatarOriginalRelativePath = path;
user.AvatarCroppedAbsolutePath = "";
user.AvatarCroppedFileName = "";
user.AvatarCroppedRelativePath = "";
userRepo.Update(user);
}
else
{
Logger.Error("User is null. Id: " + userId.ToString());
}
kernel.Release(userRepo);
kernel.Release(logger);
kernel.Dispose();
}
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("/Account/Avatar", UriKind.Relative);
return response;
});
});
}
Following Error get :-
"Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'. Parameter name: content"
There's no standard Task.Then method in .NET framework, and I couldn't find any implementation details in the code you posted. I'd assume it was taken from here:
Processing Sequences of Asynchronous Operations with Tasks
If that's the case, you may be loosing AspNetSynchronizationContext context inside your Task.Then lambdas, because the continuation may happen on a different ASP.NET pool thread without proper synchronization context. That would explain why HttpContent becomes invalid.
Try changing the implementation of Task.Then like this:
public static Task<T2> Then<T1, T2>(this Task<T1> first, Func<T1, Task<T2>> next)
{
if (first == null) throw new ArgumentNullException("first");
if (next == null) throw new ArgumentNullException("next");
var tcs = new TaskCompletionSource<T2>();
first.ContinueWith(delegate
{
if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);
else if (first.IsCanceled) tcs.TrySetCanceled();
else
{
try
{
var t = next(first.Result);
if (t == null) tcs.TrySetCanceled();
else t.ContinueWith(delegate
{
if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled) tcs.TrySetCanceled();
else tcs.TrySetResult(t.Result);
}, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (Exception exc) { tcs.TrySetException(exc); }
}
}, TaskScheduler.FromCurrentSynchronizationContext());
return tcs.Task;
}
Note how the continuations are now scheduled using TaskScheduler.FromCurrentSynchronizationContext().
Ideally, if you can use .NET 4.5, you should be using async/await: Using Asynchronous Methods in ASP.NET 4.5. This way, the thread's synchronization context is automatically captured for await continuations.
The following may facility porting:
Implementing Then with Await.
Related
I created a web app using asp.net-mvc and Jquery
when I added the below code my application automatically stop running without throwing any error, I don't know Whether it is my visual studio 19 or IIS which is being crashed
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
To verify I created an asp.net mvc sample project and paste the above code in the index page but the same problem comes
Image
what can I do to solve this?
Do you have
enctype="multipart/form-data"
property in your form element?
<form id="upload">
<input type="file" id="file" class="form-control">
</form>
Jquery
$('#upload').submit(function (e) {
e.preventDefault(); // stop the standard form submission
var File_Name = $("#file").prop('files')[0].name;
var ext = File_Name.split('.').pop();
if (ext == "pdf" || ext == "docx" || ext == "doc" || ext == "png" || ext ==
"jpg" || ext == "jpeg" || ext == "txt") {
var lastIndex = $("#file").prop('files')[0].name.lastIndexOf(".") + 1;
var form = new FormData();
form.append("file", $("#file").prop('files')[0]);
$.ajax({
url: '/Main/SaveDocument',
type: 'POST',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
if (data == "999") {
swal("Note", "Some Error Occurred. File Not uploaded successfully.", "error");
}
},
error: function (xhr, error, status) {
console.log(error, status + " " + xhr);
}
});
}
else {
swal("Note", "File Type Not Supported.", "warning");
}
});
C#
public ActionResult SaveDocument()
{
//file
var file = System.Web.HttpContext.Current.Request.Files["file"];
var CheckCnic = hr_FTPEntities.File_description.Where(x => x.uploader_CNIC == userCNIC).FirstOrDefault();
if(CheckCnic == null)
{
HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
if (filebase.ContentLength > 0)
{
var fileName = Path.GetFileName(filebase.FileName);
string path = Path.Combine(Server.MapPath(basePath + departmentName) + "/");
File_description file_Description = new File_description();
int fileCount = hr_FTPEntities.File_description.Select(x => x).ToList().Count + 1;
int lastIndexOfDot = fileName.LastIndexOf(".") - 1;
string finalFileName = fileName.Substring(0, lastIndexOfDot) + "_" + fileCount + fileName.Substring(lastIndexOfDot + 1);
file_Description.file_name = finalFileName.ToString();
try
{
filebase.SaveAs(path + (finalFileName));
}
catch(Exception ex)
{
return Json("999");
}
}
return Json("000");
}
else
{
return Json("888");
}
}
You could try to use the below code:
View(Index.cshtml) :
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
fileData.append('username', 'test');
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Controller (HomeController.cs):
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Make sure your IIS site contains the upload folder and enough permission to access the folder.
If you still face the same issue then try to use the different browser.
check event viewer logs or try to collect the dup and analyze the dump using the DebugDiag tool.
I have a controller like this:
public ActionResult CargaCSV(HttpPostedFileBase archivo)
{
List<string[]> registros = new List<string[]>();
confService = new ConfiguracionService();
if (archivo.ContentLength > 0)
{
StreamReader sR = new StreamReader(archivo.InputStream);
string linea;
string resultado = "";
var f = 0;
while ((linea = sR.ReadLine()) != null)
{
if (f == 0)
{
f++;
continue;
}
else
{
String[] registros_ = linea.Split(',');
registros.Add(registros_);
}
}
sR.Close();
ViewBag.Message = resultado;
confService.GuardarMatrizCsv(registros,usuarioCaptura);
}
return Json(registros);
}
As you can see I return result into div:
ViewBag.Message = resultado;
View:
<div class="" style="height: 150px; overflow: auto; margin-bottom:10px;">
<pre id="resultado">#ViewBag.Message</pre>
</div>
That I want to do is to cancel all proccess if (archivo.ContentLength > 0) return null and return: ViewBag.Message = "you need attach file to load it"; and stop all process
How can I achieve this?
Update:
I call CargaCSV method with ajax call:
$("#btnCargarCsv").on("click", function () {
var data = new FormData();
data.append("archivo", $("#archivo")[0].files[0]);
$.ajax({
"type": "POST",
"url": "/Configuracion/CargaCSV",
"contentType": false,
"processData": false,
"data": data,
success: function (s) {
var result = $("#resultado");
result.text("");
result.append("<table>");
result.append("<tr>");
result.append("<th> Unidad </th>");
result.append("<th> CR Mínimo </th>");
result.append("<th> CR Máximo </th>");
result.append("<th> % Mínimo </th>");
result.append("<th> % Máximo </th>");
result.append("</tr>");
for (var i = 0; i < s.length; i++) {
var val = s[i];
result.append("<tr>");
result.append("<td> " + val[0] + " </td>");
result.append("<td> " + val[1] + " </td>");
result.append("<td> " + val[2] + " </td>");
result.append("<td> " + val[3] + " </td>");
result.append("<td> " + val[4] + " </td>");
result.append("</tr>");
}
result.append("</table>");
}
});
});
So here I append data into table and show data into pre html tag "resultado"
Your returning a JsonResult, not a ViewResult, so setting a ViewBag property is pointless (ViewBag is for passing data to a View) and your
<pre id="resultado">#ViewBag.Message</pre>
element will only ever display the initial value of ViewBag.Message when the page is first rendered.
You need to return the message in your JsonResult and test it in the ajax success method.
Change the controller code to return different values based on your condition
public ActionResult CargaCSV(HttpPostedFileBase archivo)
{
if (archivo.ContentLength = 0)
{
string message = "you need attach file to load it";
return Json( new { message = message });
}
.... // your code to process the file
return Json(new { registros = registros });
}
and change the code in the success callback to test the result
success: function (data) {
if (data.message) {
$('#resultado').text(data.message);
} else if (data.registros) {
var result = $("#resultado");
....
for (var i = 0; i < data.registros.length; i++) {
var val = data.registros[i];
....
}
result.append("</table>");
}
}
As a side note, you could simplify your script by generating the <table> and its headings (which should be in a <thead> element) in the view (and style it using display: none;and just add the <tr> elements inside its <tbody> element (and then show/hide the table in the success callback), for example
<table id="resultstable" style="display:none">
<thead>
....
</thead>
<tbody id="results"></tbody>
<table>
Script
var table = $('#resultstable');
var results = $('#results');
var message = $('#resultado');
$('btnCargarCsv').on('click', function () {
....
$.ajax({
....
success: function (data) {
if (data.message) {
message.text(data.message);
table.hide();
} else if (data.registros) {
results.empty(); //remove any existing rows
table.show();
for (var i = 0; i < data.registros.length; i++) {
var val = data.registros[i];
var row = $('<tr></tr>');
for(int j = 0; j < val.length; j++) {
row.append($('<td></td>').text(val[j]));
}
results.append(row);
}
}
}
});
});
In addition, you should be testing if the value of the file input is null before making the ajax call (and cancel the ajax call and display the message if it is) to prevent an unnecessary call to the server.
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>
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);
}
});
In below code first am allowing the user to select the option from the drop down list and than allows to browse the file.
Code:
function choice() {
var box = dhtmlx.modalbox({
text: "<div id='form_in_box'><div>Choose a File to Convert <hr/><label>Filename: <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Create PDF' style='width: 86px' onclick='Convert(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
});
}
function Convert(box) {
var ch = document.getElementById('choice');
var file = document.getElementById('file');
if (file.value == "") {
alert("Choose a file to convert");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Convert', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('File successfully conveted to PDF');
}
};
xhr.send(fd);
}
In ch the drop down option gets saved.
I want to send ch value to the controller
Controller code:
public ActionResult Convert(HttpPostedFileBase file, FormCollection data)
{
string choice = data["choice"];
how can i send it?
You could add it to the FormData:
var fd = new FormData();
fd.append('file', file.files[0]);
fd.append('choice', ch.value);
and your controller action may now look like this:
public ActionResult Convert(HttpPostedFileBase file, string choice)
{
...
}