I return multiple json objects but i don't know how to return that objects. I want to get returned json objects and send them to ajax request. This is my ActionResult:
public ActionResult AutoCompleteEventName(string eventName)
{
Event ev = new Event();
ev.Name = eventName;
var searchEvent = EventService.Instance.Search(ev);
var totalCount = EventService.Instance.SearchCount(ev);
}
If you want to send object's list, you can do it with this way:
var yourObjectList = EventService.Instance.LoadSomeEvents();
List<object> objectList = new List<object>();
foreach (var event in yourObjectList)
{
objectList.Add(new
{
id = event.Id,
name = event.Name,
});
}
return Json(objectList, JsonRequestBehavior.AllowGet);
return Json(new { searchEvent = searchEvent , totalCount = totalCount }, JsonRequestBehavior.AllowGet)
in controller
return result as below
var returnField = new { searchEvent = "searchEvent", totalCount = totalCount.ToString() };
return Json(returnField, JsonRequestBehavior.AllowGet);
in Ajax Request
success: function (data) {
var searchEvent = data.searchEvent;
var totalCount =data.totalCount
}
Related
I have a string called csv that is literally just that, things like "name,lastname,age,height,etc"
Then I send it to the backend like this..
var csv = exportRequests.GetCSV();
var filename = string.Format("{0}-{1}-{2:yyyy-MM-dd_hh-mm-ss-tt}.csv", "Request", requestStatus.ToUpperInvariant(), DateTime.Now);
var stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(csv);
writer.Flush();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("text/csv");
//var test = new FileDetailViewModel();
//test.Name = filename;
//test.Rows = csv;
return Ok(result);
I then read it on the backend, but where is the actual content?? Surely the bytes should be somewhere. The content property only has the headers.. This is taking place on an old system using $.ajax to make the call.
Thanks
I do not think it is possible to read content via HttpResponseMessage in JavaScript. You can only download content.
public HttpResponseMessage GetCsv()
{
var csv = exportRequests.GetCSV();
var filename = string.Format("{0}-{1}-{2:yyyy-MM-dd_hh-mm-ss-tt}.csv", "Request", requestStatus.ToUpperInvariant(), DateTime.Now);
var stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(csv);
writer.Flush();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
return result;
}
download script
window.open('/api/controller/GetCsv', '_blank', '');
If you want to display csv content you can use the following code
[HttpPost]
public String GetCsv()
{
return exportRequests.GetCSV();
}
script
$('#btngetcsv').click(function() {
$.ajax({
url: "/api/controller/GetCsv",
data: {},
type: "Post",
dataType: "Json",
success: function(result) {
var arr = csvToArray(result);
for (var i = 0; i < arr.length; i++) {
var name = arr[i].name;
var lastname = arr[i].lastname;
//etc...........
}
},
error: function() {
}
});
});
function csvToArray(str, delimiter = ",") {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
const rows = str.slice(str.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function(row) {
const values = row.split(delimiter);
const el = headers.reduce(function(object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}
This is a basic passing of values from view to controller, but this does not seek to work.When I click the update button that functions to update the record in the database, the values from view, does not correctly pass the values to controller. Upon putting debugger in the javascript, the each variables were able to correctly got its values and evn the object where they are stored.
What could possible the reason for this problem?
here's the button onclick event code in Javascript.
$('#updatePrescription').click(function () {
debugger;
ValidateFields();
var drugListIsEmpty = CheckDrugList();
var error = $(".text-danger").length;
if (error == 0 && !drugListIsEmpty) {
debugger;
var prescription = [];
var template = {};
template.templateName = $("#prescriptionTemplateName").val();
template.templateTypeId = $('input[name=templateTypeId]:checked').val();
template.prescriptionTemplateItemList = [];
template.instructionId = $('.instruction').val();
template.frequencyId = $('.frequency').val();
template.day = $('.inputDays').val();
template.quantity = $('.inputQuantity').val();
template.dispenseLocationId = $('.selectDispenseLocation').val();
template.statusId = $('.status').val();
//template.categoryId = $('.templateCategory').filter(":visible").last().val();
template.templateId = $('#prescriptionTemplateId').val();
//if (template.categoryId == null) {
// template.categoryId = 0;
//}
var x = 0;
$('#tblPrescriptionSaveTemplateBody tr').each(function (key, value) {
debugger;
var row = $(this).closest('tr');
var next_row = $(row).next();
var drugId = $(value).find('.drugId').val();
var dosage = $(value).find('.inputDosage').val();
var dosageUnitId = $(value).find('.selectUnitId').val();
var statusId = "41";
var remarks = $(value).find('.inputDescription').val();
var groupId = $(value).find('.inputGroupNo').val();
var unit = $(value).find('.selectUnitId').val();
var prescriptionTemplateItemId = $(value).find('.prescriptionTemplateItemId').val();
x++;
var obj = {
// templateId: prescriptionTemplateId,
prescriptionTemplateId: template.templateId,
prescriptionTemplateItemId: prescriptionTemplateItemId,
drugId: drugId,
dosage: dosage,
dosageUnitId: dosageUnitId,
instructionId: template.instructionId,
frequencyId: template.frequencyId,
day: template.day,
quanitity: template.quantity,
unit: unit,
remarks: remarks,
dispenseLocationId: template.dispenseLocationId,
groupId: groupId,
statusId: template.statusId
}
template.prescriptionTemplateItemList.push(obj);
//prescription.push(obj)
})
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(template),
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href = '/WestMedicinePrescriptionTemplate/Index';
}
});
}
});
This is expected to pass the result of model in parameter "newtemplate" in the controller, but it results to null
public ActionResult UpdateTemplate([FromBody] PrescriptionTemplateVM newtemplate)
{
int empId = Convert.ToInt32(HttpContext.Session.GetInt32("EmployeeId"));
var notif = "Update Failed.";
try
{
if (ModelState.IsValid)
{
bool updateSuccessful = _prescription.UpdatePrescriptionTemplateAndItems(newtemplate, empId);
if (updateSuccessful)
{
notif = "Update Successful.";
}
}
}
catch (Exception ex)
{
notif = ex.Message;
}
return Json(new { notification = notif });
}
What could be the problem in the code
do like this:
[HttpPost]
public ActionResult UpdateTemplate(PrescriptionTemplateVM newtemplate)
You need to make sure that you are using the same variables names that you defined in PrescriptionTemplateVM
and dont convert the data to Json. do like this:
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: {newtemplate: template},
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href =
'/WestMedicinePrescriptionTemplate/Index';
}
});
I have three forms in the same container, all the actions use a objectId, so i wanna apply the objectId and send a function.
Obs: unfortunately i need to use ES5.
var doRequest = function(someId){
return function(reqFunction){
return reqFunction(someId);
};
};
var partial = doRequest("mongoId");
var getRequest = partial(function(){
});
var postRequest = partial(function(){
});
controllerAlias.getRequest = getRequest;
controllerAlias.postRequest = postRequest;
Curry is working, maybe is just missing one return function to do the proper assignations. Please check:
var doRequest = function(someId){
return function(reqFunction){
return reqFunction(someId);
};
};
var partial = doRequest("mongoId");
var getRequest = partial(function(id){
return function(){console.log('in getRequest: ' + id)};
});
var postRequest = partial(function(id){
return function(){console.log('in postRequest: ' + id)};
});
const controllerAlias = {};
controllerAlias.getRequest = getRequest;
controllerAlias.postRequest = postRequest;
controllerAlias.getRequest();
controllerAlias.postRequest();
I have a Web-API method that is returning JSON and I want the array structure to look like this:
[ [123, 1.1], [222, 3.9] ]
My Web API controller is returning JSON in the following format:
[{"CreatedDate":1314736440,"Reading":20.0}, "CreatedDate":1314779640,"Reading":7.9}]
Web API Controller:
[HttpGet]
public HttpResponseMessage AllJson()
{
using (var ctx = new SomeContext())
{
var records = ctx.DataX.ToList();
var dtos = Mapper.Map<...>(records);
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject(dtos), Encoding.UTF8, "application/json")
};
}
}
DTO
public class DtoModel
{
public int CreatedDate { get; set; }
public double Reading { get; set; }
}
Sample Javascipt:
var seriesData = [];
$.getJSON("api/xxx/AllJson ", function (data) {
$.each(data, function (key, val) {
seriesData.push(val.CreatedDate.toString() + " ," + val.Reading.toString());
console.log(val.CreatedDate + " ," + val.Reading);
});
});
You need to create an a single array containing many arrays of length 2.
See this code:
$.getJSON("api/xxx/AllJson")
.done(function (data) {
var processedJson = new Array();
$.map(data, function (obj, i) {
processedJson.push([obj.CreatedDate, obj.Reading]);
});
FunctionToDoSomethingWithYourDataStructure(processedJson);
});
I think this might solve your problem..
structure wise, this should look like [[a,b],[c,d]];
var createSeriesData = function(){
seriesData = [];
JSON_obj = JSON.parse('[{"CreatedDate":1314736440,"Reading":20.0},{"CreatedDate":1314779640,"Reading":7.9}]');
for(var key in JSON_obj){
if(JSON_obj.hasOwnProperty(key)){
seriesData[key] = [];
seriesData[key].push(JSON_obj[key].CreatedDate.toString());
seriesData[key].push(JSON_obj[key].Reading.toString());
}
}
console.log(seriesData);
}
I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps