javascript function pass object with null values - javascript

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

Related

autocomplete to avoid tab operation for textbox

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. ");
}
}
});

How to Pass List using Ajax call to Spring MVC Controller

I have holding object as follows:
public class Transfer implements Serializable {
private Integer transferId;
private Integer transferTypeId;
private String storeId;
private String userId;
private Integer titleId;
private Integer statusId;
private String inWorkerId;
private String outWorkerId;
private Date createDt;
private Date updateDt;
// getters & setts
}
And I have var reqRow that need to be sent to the controller
function onClickSave(){
var rows = $('#transferEditGrid').jqGrid('getRowData');
var reqRow = [];
for (i = 0; i < rows.length; i++)
{
var rowObj = {};
rowObj.storeId = rows[i].storeId;
rowObj.inWorkerId = rows[i].inWorkerId;
rowObj.outWorkerId = rows[i].outWorkerId;
rowObj.transferTypeId = rows[i].transferTypeId;
rowObj.statusId = rows[i].statusId;
rowObj.storeId = rows[i].storeId;
reqRow.push(rowObj);
}
//send reqRow to the Controller
$.ajax({
type:'POST',
url:'${contextPath}/resource-transfer/update.do',
dataType:"json",
data : {rows : reqRow},
//data:JSON.stringify(reqRow),
success:function(response){
alert("success");
}
});
}
The controller is following :
#RequestMapping(value = "/update", method = { RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
#ResponseBody
public String transferUpdate(#RequestBody List<Transfer> rows) throws JSONException, InterruptedException {
System.out.println("in transfer update section");
return null;
}
Why I could not pass the array object to the controller?
Did I misunderstand the usage of the Ajax call?
Thank you
First, wrap List to another java object
public class TransferDTO {
private List<Transfer> rows;
// getter & setter
}
Use this inplace of List<Transfer> in your endpoint.
public String transferUpdate(#RequestBody TransferDTO data)
Specify contentType in your AJAX post
contentType: 'application/json'
Manually stringify the data
data : JSON.stringify({rows: reqRow})
Java code
#Controller
public class ContractController {
#RequestMapping(value="all/contract/change/detail", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
#ResponseStatus(HttpStatus.OK)
public List<ContractAndBidReceiveChangeDetailModel> getAllContractAndBidReceiveChangeDetail(#RequestBody List<ContractReceivedChangedActivityCodesModel> allChangedActivityCodesModel) {
List<ContractAndBidReceiveChangeDetailModel> allContractAndBidChangeDetails = null;
if (CollectionUtils.isNotEmpty(allChangedActivityCodesModel)) {
allContractAndBidChangeDetails = allChangedActivityCodesModel
.stream()
.map(this::getContractAndBidReceiveChangeDetail)
.collect(Collectors.toList());
}
return allContractAndBidChangeDetails;
}
} // end of controller class
#JsonAutoDetect(
creatorVisibility = JsonAutoDetect.Visibility.NONE,
fieldVisibility = JsonAutoDetect.Visibility.NONE,
getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE
)
public class ContractReceivedChangedActivityCodesModel {
private String rowId;
private Long bidId;
private Long planId;
private Long optionCodeId;
private Long activityCodeId;
private Long activityPackageId;
private String activityCodeNoAndName;
private String planName;
// constructors
#JsonProperty
public String getRowId() {
return rowId;
}
public void setRowId(String rowId) {
this.rowId = rowId;
}
//others getters and setters
}
JQuery code. Make sure you make the same json rquest that spring is expecting. Spring will automatically map this json to your java List
function getDetailRow(url, requestData, $caret, action) {
$spinner.show();
$.ajax({
url: url,
data : requestData,
dataType: "json",
type: "POST",
contentType: "application/json",
success: function(response) {
if (!$.isEmptyObject(response)) {
switch(action){
case "expandLink":
insertDetailRow($caret, response);
break;
case "expandAllLinks":
$.each(response, function(index, changeDetailResponse) {
var caretId = changeDetailResponse.rowId;
let $caret = $('#' + caretId);
insertDetailRow($caret, changeDetailResponse);
});
break;
}
}
$spinner.hide();
}, error: function(xhr, status, error){
$spinner.hide();
if (xhr.status == 500) {
var errorResponse = xhr.responseText;
if (errorResponse) {
alert(errorResponse);
}
}
}
});
}
function getRequestJson(requestObject) {
let requestJson = null;
if (requestObject != null) {
requestJson = JSON.stringify(requestObject);
}
return requestJson;
}
function getRequestObject($caret) {
let requestObject = null;
if ($caret.length > 0) {
let rowId = $caret.attr("id");
let bidId = $caret.attr("bidId");
let planId = $caret.attr("planId");
let optionCodeId = $caret.attr("optionCodeId");
let activityCodeId = $caret.attr("activityCodeId");
let activityPackageId = $caret.attr("activityPackageId");
requestObject = new Object();
requestObject.rowId = rowId;
requestObject.bidId = bidId;
requestObject.planId = planId;
requestObject.optionCodeId = optionCodeId;
requestObject.activityCodeId = activityCodeId;
requestObject.activityPackageId = activityPackageId;
}
return requestObject;
}
let caretsWithoutDetailRow = new Array();
let requestObjects = null;
// process caretsWithoutDetailRow Array with some logic so it contains some elements
if (caretsWithoutDetailRow.length > 0) {
requestObjects = new Array();
$.each(caretsWithoutDetailRow, function(index, $caret) {
let requestObject = getRequestObject($caret);
requestObjects.push(requestObject);
});
}
if (requestObjects != null && requestObjects.length > 0) {
let requestObjectsJson = getRequestJson(requestObjects);
let url = '<c:url value = "/all/contract/change/detail"/>';
getDetailRow(url, requestObjectsJson, null, 'expandAllLinks');
}

Liferay - Select item filled with json responseData

It's my first post on stackoverflow so I hope I won't make too many mistakes.
I've a problem with filling Java List and sending it to aui:select as options. My goal is to fill aui:select dynamically whenever one of their options is changed. For example: if you change first select item (county), second and third items (community and city respectively) are emptied and then filled with data dependent on selected county.
I've come to a conclusion that whenever there's a "mvcPath" parameter in Query String Parameters this code basically copies code from the whole page. This code works well whenever there's no "mvcPath" though. Sadly, I need this parameter to change pages (from search results to selected result details).
Image showing badly filled select item
Image showing correctly filled select item
Java code:
#Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws IOException, PortletException {
String communityName = "";
long communityId = 0;
String cityName = "";
long cityId = 0;
String countySelected = ParamUtil.getString(resourceRequest, "countySelected");
long countySelectedId = ParamUtil.getLong(resourceRequest, "countyDictionaryId");
String communitySelected = ParamUtil.getString(resourceRequest, "communitySelected");
long communitySelectedId = ParamUtil.getLong(resourceRequest, "communityDictionaryId");
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
if (countySelected.equalsIgnoreCase("countySelected") && countySelectedId != 0) {
System.out.println("County id: " + countySelectedId);
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
for (CommunityDictionary community : communities) {
if (community.getCountyDictionaryId() == countySelectedId) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
System.out.print(jsonArray.toString());
}
}
} catch (SystemException e) {
e.printStackTrace();
}
} else if (countySelected.equalsIgnoreCase("countySelected") && countySelectedId == 0) {
System.out.println("No county chosen.");
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
for (CommunityDictionary community : communities) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
} catch (SystemException e) {
e.printStackTrace();
}
}
if (communitySelected.equalsIgnoreCase("communitySelected") && communitySelectedId != 0) {
System.out.println("Community id: " + communitySelectedId);
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
for (CityDictionary city : cities) {
if (city.getCommunityDictionaryId() == communitySelectedId) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
System.out.print(jsonArray.toString());
}
}
} catch (SystemException e) {
e.printStackTrace();
}
} else if (communitySelected.equalsIgnoreCase("communitySelected") && communitySelectedId == 0) {
System.out.println("No community chosen.");
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
for (CityDictionary city : cities) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
} catch (SystemException e) {
e.printStackTrace();
}
}
PrintWriter writer = resourceResponse.getWriter();
writer.write(jsonArray.toString());
writer.flush();
super.serveResource(resourceRequest, resourceResponse);
}
Script:
<aui:script>
AUI().use('aui-base', 'aui-io-request', 'aui-node',
function(A) {A.one("#<portlet:namespace />countySelect").on('change', function() {
A.io.request('<%= selectionChangedURL %>',
{
method : 'POST',
data : {
"<portlet:namespace />countyDictionaryId" : A.one("#<portlet:namespace />countySelect").val(),
'<portlet:namespace />countySelected' : 'countySelected'
},
dataType : 'json',
on : {
success : function() {
var communitiesList = this.get('responseData');
A.one('#<portlet:namespace />communitySelect').empty();
A.one('#<portlet:namespace />citySelect').empty();
A.one('#<portlet:namespace />communitySelect').prepend("<option value='0'> </option>");
for (var i in communitiesList) {
console.info(communitiesList[i]);
A.one('#<portlet:namespace />communitySelect').append("<option value='" + communitiesList[i].communityDictionaryId + "'>" + communitiesList[i].communityName + "</option>");
}
}
}
});
});
A.one("#<portlet:namespace />communitySelect").on('change', function() {
A.io.request('<%= selectionChangedURL %>',
{
method : 'POST',
data : {
"<portlet:namespace />communityDictionaryId" : A.one("#<portlet:namespace />communitySelect").val(),
'<portlet:namespace />communitySelected' : 'communitySelected'
},
dataType : 'json',
on : {
success : function() {
var citiesList = this.get('responseData');
A.one('#<portlet:namespace />citySelect').empty();
A.one('#<portlet:namespace />citySelect').prepend("<option value='0'> </option>");
for (var i in citiesList) {
console.info(citiesList[i]);
A.one('#<portlet:namespace />citySelect').append("<option value='" + citiesList[i].cityDictionaryId + "'>" + citiesList[i].cityName + "</option>");
}
}
}
});
});
});
After some changes in server-side code I managed to fix this issue. I'm not really sure how did as small changes as those helped but I'm happy to close this thread.
This is the server-side code:
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
throws IOException, PortletException {
String communityName = "";
long communityId = 0;
String cityName = "";
long cityId = 0;
String countySelected = ParamUtil.getString(resourceRequest, "countySelected");
long countySelectedId = ParamUtil.getLong(resourceRequest, "countyDictionaryId");
String communitySelected = ParamUtil.getString(resourceRequest, "communitySelected");
long communitySelectedId = ParamUtil.getLong(resourceRequest, "communityDictionaryId");
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
if (countySelected.equalsIgnoreCase("countySelected")) {
try {
int communitiesCount = CommunityDictionaryLocalServiceUtil.getCommunityDictionariesCount();
List<CommunityDictionary> communities = CommunityDictionaryLocalServiceUtil.getCommunityDictionaries(0,
communitiesCount);
if (countySelectedId == 0) {
for (CommunityDictionary community : communities) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
} else {
for (CommunityDictionary community : communities) {
if (community.getCountyDictionaryId() == countySelectedId) {
communityName = community.getCommunityName();
communityId = community.getCommunityDictionaryId();
JSONObject communityObject = JSONFactoryUtil.createJSONObject();
communityObject.put("communityName", communityName);
communityObject.put("communityDictionaryId", communityId);
jsonArray.put(communityObject);
}
}
}
} catch (SystemException e) {
e.printStackTrace();
}
}
if (communitySelected.equalsIgnoreCase("communitySelected")) {
try {
int citiesCount = CityDictionaryLocalServiceUtil.getCityDictionariesCount();
List<CityDictionary> cities = CityDictionaryLocalServiceUtil.getCityDictionaries(0, citiesCount);
if (communitySelectedId == 0) {
for (CityDictionary city : cities) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
} else {
for (CityDictionary city : cities) {
if (city.getCommunityDictionaryId() == communitySelectedId) {
cityName = city.getCityName();
cityId = city.getCityDictionaryId();
JSONObject cityObject = JSONFactoryUtil.createJSONObject();
cityObject.put("cityName", cityName);
cityObject.put("cityDictionaryId", cityId);
jsonArray.put(cityObject);
}
}
}
} catch (SystemException e) {
e.printStackTrace();
}
}
PrintWriter writer = new PrintWriter(resourceResponse.getPortletOutputStream());
writer.write(jsonArray.toString());
writer.flush();
super.serveResource(resourceRequest, resourceResponse);
}

#Controller returns empty page with "ok"

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.

Cannot display returned property values from MVC controller with .ajax call

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.");
}
});

Categories