I'm trying to save a file with js from modal window. I save it all right but then I'm redirected to the page with only "ok" written on it.
I mean this:
My js looks like:
var name = $('#upload-track-name').val();
var description = $('#upload-track-description').val();
var file = document.getElementById('input-file').files[0];
var isValidate = true;
if (name.trim() == '') {
$('#error-upload-track-name').show();
isValidate = false;
}
if (!file) {
$('#error-upload-track-file').show();
isValidate = false;
}
if (!isValidate) {
return;
}
$.ajax({
url: '/tracks/upload',//I see this empty page on this url
type: 'post',
data: {
file: file,
name: name,
description: description
},
success: function (data){
if (data == 1) {
$('#error-upload-track-file').hide();
$('#error-upload-track-name').show();
} else if (data == 2) {
$('#error-upload-track-name').hide();
$('#error-upload-track-file').show();
} else {
$('#modal-upload-success').show();
}
})
And here is my #Controller:
#ResponseBody
#RequestMapping(value = TracksGeopointsRoutes.UPLOAD, method = RequestMethod.POST)
public String uploadTrack(#RequestParam MultipartFile file,
#RequestParam String name,
#RequestParam(required = false, defaultValue = "") String description,
Model model){
TracksGeopointsDoc tracksGeopointsDoc = new TracksGeopointsDoc();
if (name.equals("")) {
return "1";
}
if (file.getSize() == 0 || file == null){
return "2";
}
ObjectId fileId = fileService.saveWithDelete(file, null);
tracksGeopointsDoc.setFile(fileId);
tracksGeopointsDoc.setUploadDate(new Date());
tracksGeopointsDoc.setName(name);
tracksGeopointsDoc.setDescription(description);
tracksGeopointsService.saveTrack(tracksGeopointsDoc);
try {
File convFile = tracksGeopointsService.convert(file);
String s = convFile.getAbsolutePath();
mySaxParser.setUpMySaxParser(convFile.getAbsolutePath(), tracksGeopointsDoc.getId(), convFile.getName());
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
I suspect that it is because of #ResponseBody annotation. And if I am right can anyone tell me how can I avoid this.
Related
I am doing master/detail using this article as a guide, my case is a little different as I have five different details for single master table and each one with totally different details/columns. I want my users to enter all rows in selected detail table and pass these rows with the master to the controller, but passed parameter is always null. I searched a lot without success.
Solution in this post did not work for me and a couple of others in different forums.
Here is my code:
//JobOrderMaster Action:
[HttpPost]
public ActionResult JobOrderMaster(WorkOrder objJobOrder, string btnPrevious, string btnNext)
{
ViewBag.Project_Id = new SelectList(db.Projects, "Project_Id", "Project_Name_e");
if (btnNext != null)
{
if (ModelState.IsValid)
{
workOrderId = Guid.NewGuid();
JobOrderViewModel objWorkOrder = GetJobOrder();
objWorkOrder.WorkOrder_Id = workOrderId;
objWorkOrder.Start_Date = objJobOrder.Start_Date;
objWorkOrder.End_Date = objJobOrder.End_Date;
objWorkOrder.Project_Id = objJobOrder.Project_Id;
objWorkOrder.Subject = objJobOrder.Subject;
objWorkOrder.WorkOrder_Date = DateTime.Now;
objWorkOrder.Created_Date = DateTime.UtcNow;
objWorkOrder.WorkOrder_Type = objJobOrder.WorkOrder_Type;
objWorkOrder.Created_By = User.Identity.GetUserName();
objWorkOrder.Descriptions = objJobOrder.Descriptions;
ViewBag.WorkOrderId = objWorkOrder;
switch ((int)objJobOrder.WorkOrder_Type)
{
case 1: return View("JobOrderDetails");
case 2: return View("InHouseMaintenance");
case 3: return View("CustomerSideMaintenance");
case 4: return View("SiteSurvey");
case 5: return View("Installation");
default: return View("JobOrderDetails");
}
}
}
return View();
}
//JobOrderDetails Action:
//string expenseMaster;
[HttpPost]
public ActionResult JobOrderDetails(WorkOrderDetail[] objWorkOrderDetail)
{
WorkOrder objWorkOrder = new WorkOrder();
WorkOrderDetail details = new WorkOrderDetail();
JobOrderViewModel objJobOrder = GetJobOrder();
if (objJobOrder.WorkOrder_Id != null)
{
objWorkOrder.WorkOrder_Id = objJobOrder.WorkOrder_Id;
objWorkOrder.Start_Date = objJobOrder.Start_Date;
objWorkOrder.End_Date = objJobOrder.End_Date;
objWorkOrder.Project_Id = objJobOrder.Project_Id;
objWorkOrder.Subject = objJobOrder.Subject;
objWorkOrder.Descriptions = objJobOrder.Descriptions;
objWorkOrder.Type_Id = objJobOrder.Type_Id;
objWorkOrder.WorkOrder_Type = objJobOrder.WorkOrder_Type;
objWorkOrder.WorkOrder_Status = objJobOrder.WorkOrder_Status;
objWorkOrder.WorkOrder_Priority = objJobOrder.WorkOrder_Priority;
objWorkOrder.WorkOrder_Date = DateTime.Now;
objWorkOrder.Created_Date = DateTime.UtcNow;
objWorkOrder.Created_By = User.Identity.GetUserName();
db.WorkOrders.Add(objWorkOrder);
}
int detailId = 1;
//if (btnNext != null)
//{
if (ModelState.IsValid)
{
foreach (var item in objWorkOrderDetail)
{
details.WorkOrder_Id = objWorkOrder.WorkOrder_Id;
details.Category_Id = item.Category_Id;
details.Detail_Id = detailId;
details.Qty = item.Qty;
db.WorkOrderDetails.Add(details);
detailId++;
}
try
{
db.SaveChanges();
RemoveJobOrder();
return View("Index");
}
catch (DbUpdateException ex)
{
string message = "";
UpdateException updateException = (UpdateException)ex.InnerException;
SqlException sqlException = (SqlException)updateException.InnerException;
foreach (SqlError error in sqlException.Errors)
{
message = string.Format("{0} Error '{1}' occurred in {2} at {3}\n\n\r\n",
message
, error.Number
, error.Message
, error.LineNumber);
}
ViewBag.errorMessage = message;
clsGeneralMethods.ErrorLog(message);
return View("Error");
}
catch (DbEntityValidationException ex)
{
string message = "";
foreach (DbEntityValidationResult item in ex.EntityValidationErrors)
{
//Get entry
DbEntityEntry entry = item.Entry;
string entityTypeName = entry.Entity.GetType().Name;
//Display or log error messages
foreach (DbValidationError subItem in item.ValidationErrors)
{
message = string.Format("{0}Error '{1}' occurred in {2} at {3}\n\n\r\n",
message
, subItem.ErrorMessage
, entityTypeName
, subItem.PropertyName);
}
}
ViewBag.errorMessage = message;
clsGeneralMethods.ErrorLog(message);
return View("Error");
}
}
//}
return View();
}
//My javascript functions
function btnFinish(details) {
//alert(JSON.stringify(details));
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("JobOrderDetails")',
data: JSON.stringify({ objWorkOrderDetail: details }),
success: function (result) {
//location.reload();
},
error: function (err) {
if (err != null) {
alert('Error: ' + err.Message);
}
}
});
}
$("#btnFinish").click(function (e) {
e.preventDefault();
var claimArr = [];
claimArr.length = 0;
$.each($("#detailsTable tbody tr"), function () {
claimArr.push({
categoryId: $(this).find('td:eq(0)').html(),
descriptions: $(this).find('td:eq(1)').html(),
quantity: $(this).find('td:eq(2)').html()
});
});
var data = JSON.stringify(claimArr);
//alert(data);
$.when(btnFinish(data)).then(function (response) {
window.location.href = "../JobOrder/Index";
//console.log(response);
}).fail(function (err) {
console.log(err.Message);
window.location.href = "../JobOrder/Index";
});
});
});
action screenshot shows null values
alert msg shows object received ok in js function
The problem is that You don't have the same names of properties in JSON (JavaScript side) and your class WorkOrderDetails in C#:
WorkOrderDetails
JSON
Category_Id
categoryId
Descriptions
descriptions
Qty
quantity
Make the same names in two of these types and it should be ok.
For example:
WorkOrderDetails
JSON
categoryId
categoryId
descriptions
descriptions
quantity
quantity
I am using Autocomlete to show the list of location which come from database. User get the list as expected. but instate selecting from list user just click on the tab button and control going to next button. I want to avoid TAB operation here.Any suggestion how i will do that .
Here is my function :
$(document).ready(function () {
src = 'LocationHandler.ashx';
$('#txtLocationName').autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term,
type: $("#ddlDivision1").val()
},
success: function (data) {
Object.keys = Object.keys || function (o, k, r) { r = []; for (k in o) r.hasOwnProperty.call(o, k) && r.push(k); return r }
if (Object.keys(data).length == 0) {
$('#txtLocationName').val('');
alert('Location must be selected from the options.');
}
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
My Handler class looks like
public class LocationHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string term = context.Request["term"] ?? "";
string type = context.Request["type"] ?? "";
// type = "FM";
List<string> listLocationNames = new List<string>();
string cs = ConfigurationManager.ConnectionStrings["EGLFormsDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spIARLocationNames", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#term",
Value = term
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "#locType",
Value = type
});
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listLocationNames.Add(rdr["Name"].ToString());
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
context.Response.Write(js.Serialize(listLocationNames));
}
public bool IsReusable
{
get
{
return false;
}
}
}
this is how i solve this.
$("#txtLocationName").keydown(function (evt) {
var keyCode = evt.keyCode || evt.which;
if (keyCode == 9) {
//evt.preventDefault();
//alert("TAB not allowed111111. Please select business unit number or name from Search box. ");
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
if (evt.key === "Tab")
{
var textloc = $("#txtLocationName").val();
var specialChars = "{"
if (textloc.indexOf("{") >= 0) {
//no need to do anything
}
else {
evt.preventDefault();
alert("TAB not allowed. Please select business unit number or name from Search box. ");
}
}
});
I have action link
#Html.ActionLink(#Resources.Resource_ar.Download, "DownloadFile", new { Communicationid = item.Communicationid }, new { #class = "btn btn-success btn_Download" })
call action to download file
public ActionResult DownloadFile(string Communicationid)
{
string pathString = Settings.getSettingValue("FolderForSaveCommunicationsAttachments");
//string FullPath = Path.Combine(Server.MapPath("~/Content/UploadedAttachment/"), FileName);
string FullPath = Path.Combine(pathString, Communicationid);
Communications ObjCommunication = new Communications(int.Parse(Communicationid));
string FileName = ObjCommunication.s_FileName;
//return File(FullPath, "text/docx");
if (System.IO.File.Exists(FullPath))
{
string contentType = string.Empty;
if (FileName.Contains(".pdf"))
{
contentType = "application/pdf";
}
else if (FileName.Contains(".docx"))
{
contentType = "application/docx";
}
else if (FileName.Contains(".doc"))
{
contentType = "application/doc";
}
else if (FileName.Contains(".jpeg"))
{
contentType = "image/jpeg";
}
else if (FileName.Contains(".jpg"))
{
contentType = "image/jpg";
}
else if (FileName.Contains(".png"))
{
contentType = "image/png";
}
else if (FileName.Contains(".bmp"))
{
contentType = "image/bmp";
}
else if (FileName.Contains(".xlsx"))
{
contentType = "application/xlsx";
}
else if (FileName.Contains(".Exl"))
{
contentType = "application/Exl";
}
else if (FileName.Contains(".txt"))
{
contentType = "application/txt";
}
return File(FullPath, contentType, FileName);
}
else
{
return;
}
}
the problem is that when the file exist it return the file and download it correctly but when the file not exist I want to show alert to user tell him the file not exist what should i return
I try to return javascript("alert('file not exist')") put it gave me blank page with text i put which "alert('file not exist')"
any help with this problem
thanks in advance
You can do something like this:
if (System.IO.File.Exists(FullPath))
{ //....
}
else { return Content("Some error message"); }
But i'd rather return a 404 if that file isn't there.
On the click event of a search button I'm sending the search text as parameter to a method on the controller. That method will return back a tool object that has properties like Name and Price in it. I can see the method is returning the tool object to the javascript and I can see the object is of tool type in the javascript but I cannot get the properties out of this object. How can I do something like this: document.getElementById('QSPrice').value = data.Price
VB.net
Function TestQuickSearch(ByVal searchItem As String) As Tool
Dim QSVM As Model.SearchViewModel = New Model.SearchViewModel()
Dim returnedItem = QSVM.GetToolByItemNum(searchItem)
Return returnedItem
End Function
JavaScript
$("#btnQuickSearch").live("click", function (e) {
var searchText = document.getElementById('txtQuickSearch').value
if(searchText.length !== 0) {
var Url = '#Url.Content("~/Route/QuickSearch")';
$.ajax({
url: Url,
async: 'false',
type: 'GET',
data: {searchItem: searchText},
success: function (data) {
alert(data.Price);
},
error: function (error) {
//Show Message
}
});
} else {
//Show Message
}
});
This is what I ended doing.
vb.net Code
Function QuickSearch(ByVal searchItem As String) As JsonResult
Dim QSVM As BusinessModel.QuickSearchViewModel = New BusinessModel.QuickSearchViewModel()
Dim returnedItem = QSVM.GetToolItemByItemNum(searchItem)
Return Json(New With {Key .results = returnedItem}, JsonRequestBehavior.AllowGet)
End Function
JavaScript Code
$("#btnQuickSearch").live("click", function (e) {
var searchText = document.getElementById('txtQuickSearch').value
if(searchText.length !== 0) {
var Url = '#Url.Content("~/Route/QuickSearch")';
$.ajax({
url: Url,
async: 'false',
type: 'GET',
dataType: 'json',
data: {searchItem: searchText},
success: function (results) {
for (var key in results) {
if(results[key] !== null){
var obj = results[key];
for (var prop in obj) {
if(obj.hasOwnProperty(prop)){
switch(prop) {
case "Price":
document.getElementById('QSPrice').value = obj[prop];
break;
case "Description":
document.getElementById('QSDescription').value = obj[prop];
break;
case "Class":
document.getElementById('QSClass').value = obj[prop];
break;
case "QtyOnHand":
document.getElementById('QSQty').value = obj[prop];
break;
case "TakeOrderF":
var boolValue;
if(obj[prop] == true){
boolValue = "Yes";
}
else{
boolValue = "No";
}
document.getElementById('QSCanOrder').value = boolValue;
break;
case "Warranty":
document.getElementById('QSWarranty').value = obj[prop];
break;
}
}
}
}
else{
showMessage("Item Not Found.");
}
}
},
error: function (error) {
showMessage("Item Not Found/json error.");
}
});
} else {
//Show Message
showMessage("Item Not Found.");
}
});
I am using ReCaptcha with the javascript API on my aspx page on localhost. I read somewhere that I don't need a key as long as I use it on localhost. So, I use some random key that I found somewhere. I could render the recaptcha challenge successfully. The following is my javascript code.
Recaptcha.create("6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf", 'captchadiv',
{
tabindex: 1,
theme: "clean",
callback: Recaptcha.focus_response_field
});
//To Validate user response
function Recaptcha_IsCorrect()
{
var xmlHttpRequest;
var PageURL = document.URL;
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlHttpRequest = new XMLHttpRequest();
}
else
{
xmlHttpRequest = new ActiveXObject("Microsoft.xmlHttpRequest");
}
var challenge = Recaptcha.get_challenge();
var userResponse = Recaptcha.get_response();
var url = "../Ajax/PIAsyncAjax.asmx/ValidateReCaptcha?clientIP=127.0.0.1&privateKey=6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf&challenge=" + challenge + "&response=" + userResponse;
xmlHttpRequest.open("GET", url);
xmlHttpRequest.onreadystatechange = function ()
{
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
alert(xmlHttpRequest.responseText);
}
};
xmlHttpRequest.send();
}
The following is my code for the webservice which exposed the webmethod to validate ReCaptcha user input. I get the error "invalid-site-private-key".
namespace YADA.YADAYADA{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class PIAsyncAjax : System.Web.Services.WebService
{
[WebMethod]
public string ValidateReCaptcha(string clientIP, string privateKey, string challenge, string response)
{
bool isValid = false;
string validationResponse = "";
reCaptchaValidation validator =
new reCaptchaValidation(null,
clientIP,
privateKey,
challenge,
response);
isValid = validator.Validate();
if (isValid)
{
validationResponse = "true";
}
else
{
if (!validator.IsErrored)
{
validationResponse = "false";
}
else
{
// oh dear, something not right
if (validator.Exception != null) // an exception occurred while
// trying to validate
validationResponse = validator.Exception.ToString();
else if (validator.ValidationResult != null) // the validation web service
// returned an error code
// (other than an invalid captcha solution)
validationResponse = "web service error: " + validator.ValidationResult;
}
}
return validationResponse;
}
}
public class reCaptchaValidation
{
private string challenge, response, privateKey, ip;
private IWebProxy proxy;
public reCaptchaValidation(string clientIP, string privateKey,
string challenge, string response) : this(null, clientIP, privateKey,
challenge, response) { }
public reCaptchaValidation(IWebProxy proxy, string clientIP,
string privateKey, string challenge, string response)
{
this.proxy = proxy;
this.ip = clientIP;
this.privateKey = privateKey;
this.challenge = challenge;
this.response = response;
}
private bool _errored;
public bool IsErrored
{
get
{
return _errored;
}
}
private Exception _ex;
public Exception Exception
{
get
{
return _ex;
}
}
private string _vr;
public string ValidationResult
{
get
{
return _vr;
}
}
public bool Validate()
{
try
{
string post = "privatekey=" + HttpUtility.UrlEncode(privateKey) +
"&remoteip=" + HttpUtility.UrlEncode(ip) + "&challenge=" +
HttpUtility.UrlEncode(challenge) + "&response=" +
HttpUtility.UrlEncode(response);
WebRequest wr = HttpWebRequest.Create
("http://www.google.com/recaptcha/api/verify");
wr.Method = "POST";
if (proxy != null)
wr.Proxy = proxy;
wr.ContentLength = post.Length;
wr.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(post);
sw.Close();
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string valid = sr.ReadLine();
if (valid != null)
{
if (valid.ToLower().Trim() == "false")
{
string errorcode = sr.ReadLine();
if (errorcode != null)
{
if (errorcode.ToLower().Trim() != "incorrect-captcha-sol")
{
_vr = errorcode;
_errored = true;
return false;
}
}
}
return (valid.ToLower().Trim() == "true");
}
else _vr = "empty web service response";
sr.Close();
return false;
}
}
catch (Exception caught)
{
_errored = true;
_ex = caught;
}
return false;
}
}}
What am I doing wrong? Should I have to get a private key? Any help would be great.
Thanks in advance,
Venkat.
It works with the public and private keys that I just created. Damn, I just assumed, "localhost" would not be accepted as a legal domain-name while signing up.