Alternative to window.location.href using POST request - ASP.NET MVC - javascript

I am writing below code in Javascript to retrieve comment and navigating same page after repopulating the data
function MoveItem() {
var empId = document.getElementById('EMP_ID').value;
var commentValue = $("#RESPONSE").val();
if ($.trim(commentToSave).length > 0) {
showAjaxLoading();
var empData= "APPROVE";
var baseControllerUrl = '/Employee/EmpManagement/PushItem';
window.location.href = baseControllerUrl + "/" + empId + "?comment=" + commentValue + "&empData=" + empData + "&currentItem=" + itemData;
} else {
aet('Pelase enter comments', 'E');
}
}
In controller the method written as
[HttpGet]
public async Task<ActionResult> MoveItem(int id, string comment, string decision, string currentworkflow)
{
return RedirectToAction("EditEmpManagemnt", "EmpManagement", new { id = id });
}
I want to convert MoveItem action method to a [HttpPost] type and what all changes are needed in Javascript & action method ? Can anyone explain with a sample code.

You can send a POST request using the fetch method. We send the data with the JSON format. Replace your javascript with this:
function MoveItem() {
var empId = document.getElementById('EMP_ID').value;
var commentValue = $("#RESPONSE").val();
if ($.trim(commentToSave).length > 0) {
showAjaxLoading();
var empData = "APPROVE";
var baseControllerUrl = '/Employee/EmpManagement/PushItem';
var url = baseControllerUrl + "/" + empId;
//here we put the url as a first parameter
//then we configure the http method
//and in the body we pass in the object in JSON format
fetch(url, {
method: "POST",
body: JSON.stringify({
"comment": commentValue,
"empData": empData,
"currentItem": itemData
})
}).then(result => {
//do something with the result you get back
console.log("Completed with result: " + result);
}).catch(err => {
//if any error occured, then show it here
console.log("There is an error: " + err);
});
} else {
aet('Please enter comments', 'E');
}
}
And in your C# code just replace [HttpGet] attribute with [HttpPost]

Related

How To Call Json API from C# Useing Javascript

I made this Web API Apllication Using ASP.NET und C#
and output response from this API is Json object To can in java script Application Call this API with Ajax
this is C# Code :
public string Get()
{
string Sql3 = "(SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song,Speaker_Volume,Speaker_Availability, Speaker_Mute,Date_Time,Speaker_Status, Row_Number() over (order by Date_Time desc) as RowNumber FROM Raspi_speaker)T";
string Sql2 = "Speaker_Volume, Speaker_Status, Speaker_Availability, Speaker_Mute, Date_Time, RowNumber FROM";
string Sql = "SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song," + Sql2 + Sql3;
SqlDataAdapter adap = new SqlDataAdapter(Sql, conn);
string[] Result = new string[10];
DataTable dataTable = new DataTable();
adap.Fill(dataTable);
int i = 0;
foreach (DataRow dataR in dataTable.Rows)
{
string Val;
Val = Convert.ToString(dataR["Raspberry_name"]);
Result[i] = Val;
i++;
}
Object[] obj = {
new { RasspiName = Result}
};
if (dataTable.Rows.Count > 0)
{
return JsonConvert.SerializeObject(obj);
}
return "No Data Found";
}
}
and output is this Json Object:
[{"RasspiName":["Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Trais-Sonos-Pi","Trais-Sonos-Pi","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS"]}]
JavaScript Code is:
function Ajax(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4 && (request.status == 200)) {
var DataR = [];
DataR =JSON.parse(request.responseText)
console.log(DataR)
}
}
var url = 'http://localhost:41839/api/Musik';
request.open('GET',url ,true);
request.send()
}
My problem is that it treats the Json object as text Although I used ((JSON.parse)) Method in Java Script ... For example when I write (( console.log(DataR[ 0 ])) I get only one Letter for Example [ Instead of Value when I write (( console.log(DataR[ 0 ].RasspiName)) I get Undefined
I dont know if proplem from C# code oder From Java Script
I hope your help thanks so much
I don't understand how you defined the API Get method in the back-end code example, but I think you should set something like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string GetDashboardInfo()
{
//your code here
}
You can use Ajax to make the GET request:
function GetData() {
try {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:41839/api/Musik",
data: '',
dataType: "json",
success: OnSuccessGetData,
error: OnErrorGetData
});
}
catch (ex) {
console.log("GetData(): " + ex.toString());
}
}
function OnSuccessGetData(result) {
try {
if (result.d !== "" && result.d !== null) {
var dataSourceJson = JSON.parse(result.d);
}
else {
console.log("OnSuccessGetData: result is null!");
}
}
catch (ex) {
console.log("OnSuccessGetData(): " + ex.toString());
}
}
function OnErrorGetData(httpRequest, textStatus, errorThrown) {
try {
console.log("OnErrorGetDashboardData: " + textStatus + " " + errorThrown + " " + httpRequest);
}
catch (ex) {
console.log("OnErrorGetDashboardData(): " + ex.toString());
}
}
More about JavaScript Get request here.

Download a file through ajax request in asp.net MVC

I am trying to download file through ajax call in asp.net
my javascript:
var allData = dataSource.data();
var query = new kendo.data.Query(allData);
var data = query.filter(filters).data;
var strAccountCodes = '';
for (var i = 0; i < data.length; i++) {
strAccountCodes += data[i].AccountCode + ",";
}
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes }
});
my action method:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
return File(output, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
code is executing without any errors but it's not downloading any file.
is that anything i am missing?
You should know that AJAX call is not intended to download CSV file directly. Therefore, you can create a byte array from MemoryStream instance and store it inside Session or TempData variable, then return 'successful' state to enable redirect on AJAX success response:
public ActionResult GetHistoricalUsageApplicationFile([DataSourceRequest]DataSourceRequest request, [FromBody] string accountCodes)
{
var HistoricalUsagesData = _enrollmentManagementRepository.GetHistoricalUsageApplicationFile(accountCodes);
List<HistoricalUsageApplicationFileModel> HUApplications = _mapper.MapToNew<List<HistoricalUsageApplicationFileModel>>(HistoricalUsagesData);
//var HistoricalUsageApplication = HUReport.ToDataSourceResult(request).Data;
var output = new MemoryStream();
var writer = new StreamWriter(output, Encoding.UTF8);
writer.Write("CommodityCode,");
writer.Write("CustomerTypeCode,");
writer.Write("EnrollmentRequestId");
writer.WriteLine();
var list = HUApplications.ConvertToString();
var single = list.Aggregate((x, y) => { return string.Concat(x, y); });
writer.WriteAsync(single);
writer.Flush();
output.Position = 0;
// creates byte array from stream
TempData["Output"] = output.ToArray();
// returns successful state
return Json("Success", JsonRequestBehavior.AllowGet);
}
Second, create a controller action with GET method and pass stored byte array from Session or TempData into FileResult:
public ActionResult DownloadCSV()
{
// retrieve byte array here
var array = TempData["Output"] as byte[];
if (array != null)
{
return File(array, System.Net.Mime.MediaTypeNames.Application.Octet, "Products.csv");
}
else
{
return new EmptyResult();
}
}
Finally, handle success response to include location.href which will redirect to controller returning FileResult to download CSV file:
$.ajax({
url: '#Url.Action("GetHistoricalUsageApplicationFile", "HUProducts")',
type: 'GET',
data: { "accountCodes": strAccountCodes },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadCSV", "ControllerName")';
}
}
});
As an option, you could pass CSV file name as parameter from AJAX response using query string.
Related issue:
Creating a byte array from a stream

API Jive get categories error : Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/

i use Jive and i want to get all categories and for each category, i want to create a checkbox for each of them.
Currently, i have my array with all categories, but when i try to create checkbox, it return me this error :
" Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/ "
Someone can help me ?
///////////////// function checkbox for each category ////////////////
$("#submit_a_question").click(function(e) {
e.preventDefault();
$("#modal").addClass('is-show');
$("#ideasContainer").height((height + 100) + "px");
resizeIframe();
fieldsPlaceholder(appLang);
var categoriesToShow = categories(placeID);
var container = $('#listCheckboxCategories');
var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = $('input />', {type: 'checkbox'});
if(tileConfig.isThereFilterRadios == "Yes"){
$('#ShowCategories').show();
$('#listDropdownCategories').show();
$.each(categoriesToShow.res, function(index, value) {
CheckboxCreate.appendTo(container);
});
}
///////// function to get all categories in an array /////////
function categories(placeID){
var request = osapi.jive.corev3.places.get({
uri : '/api/core/v3/places/' + placeID
});
// var res = [];
request.execute(function(response) {
if (typeof response.error != 'undefined') {
console.log("API call failed");
} else {
console.log(response);
response.getCategories().execute(
function (res){
console.log("cat",res);
});
}
});
}
I was able to execute the call successfully by using "/places/{placeId}" in the URI as below:
osapi.jive.corev3.places.get({uri: '/places/1003'}).execute(function(response) {
console.log(response);
});
For which I have received the place object in the response, as expected:
{ type: "space",
parent: "http://localhost:8080/api/core/v3/places/1000",
placeTopics: Array(0),
displayName: "water-cooler",
iconCss: "jive-icon-space", …}
Are you sure your "placeId" has the correct value? Maybe log the URI you are sending before making the call and check if the format matches the one I have mentioned above. Thanks.

.Net Core Web API not accepting a json string field value

I have a problem whereby I would like to pass a json string as a field value but I keep getting "The input was not valid". So to be clear I have an object in my front end that I use the below to pass to my API:
let j: Settings = {} as Settings;
j.user_settings_ID = object.user_settings_ID;
j.user_ID = object.user_ID;
j.user_filter = JSON.stringify(object.user_filter);
j.user_test_filter = JSON.stringify(object.user_test_filter);
fetch('api/Profile/UpdateProfileSettings/?id=' + object.user_settings_ID, {
method: 'put',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer ' + sessionStorage.getItem('token')
},
body: "'" + JSON.stringify(j) + "'",
}).then(data => {
if (!data.ok) {
alert("Failed");
}
}).catch((ex) => {
alert("Failed");
});
In my API I have:
[HttpPut("[action]")]
public async Task<string> UpdateProfileSettings(int id, [FromBody] string obj)
{
HttpClient clientRoute = new HttpClient();
var response = await clientRoute.PutAsync("https://something.com/api/UserSettings/put/" + id, new StringContent(obj, Encoding.UTF8, "application/json"));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
I don't have a problem when I set the j.user_filter and j.user_test_filter with any normal string, but I would like to put the 'jsonified' string as the value for the field, but the Web API doesn't like it for some reason (probably because it isn't seeing it as a string but a json object perhaps)
If someone could help I would be most grateful.
Ok after messing about with this for a long time, I came up with this 'solution'.
So as #Niladri pointed out the "'" before JSON.stringify(j) was a factor but was not the only thing that needed to be changed. The main problem was actually in the controller itself.
I had this previously in my controller:
public async Task<string> UpdateProfileSettings(int id,[FromBody] string obj)
{
HttpClient clientRoute = new HttpClient();
var response = await clientRoute.PutAsync("https://something.com/api/UserSettings/put/" + id, new StringContent(obj, Encoding.UTF8, "application/json"));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
But I had to change it to:
public async Task<string> UpdateProfileSettings(int id,[FromBody] object obj)
{
HttpClient clientRoute = new HttpClient();
var response = await clientRoute.PutAsync("https://something.com/api/UserSettings/put/" + id, new StringContent(obj.ToString(), Encoding.UTF8, "application/json"));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
Notice the change of [FromBody] string obj to [FromBody] object obj and also
changed StringContent(obj, Encoding.UTF8, "application/json")) to StringContent(obj.ToString(), Encoding.UTF8, "application/json"))
My previous method with "'" before JSON.stringify(j) works if your controller [FromBody] is of string type and you aren't looking to pump a string which looks like JSON into your controller.
I apologise if this is a bad explanation but tried my best and it worked for me
This is very similar to mcc20's own fix, but I didn't get that code to work. The 2.1 framework has Issues https://github.com/aspnet/Mvc/issues/7609 and https://github.com/aspnet/Mvc/issues/7799. I got this JSON post to complex class working in 2.1: client javascript is unchanged:
var payload = JSON.stringify({ "name": document.getElementById('firstname').value, "email": document.getElementById('email').value, "captcha": grecaptcha.getResponse() });
var oReq = new XMLHttpRequest();
oReq.ContentType = "application/json";
oReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("update").innerHTML = this.responseText;
}
else document.getElementById("update").innerHTML = "not 4&200! : " + this.responseText;
};
oReq.open('POST', 'api/u');
oReq.send(payload);
and the controller has:
[Route("api/[controller]")]
// [ApiController] // works either way
public class UController : ControllerBase
{
[HttpPost]
public async Task<string> signUp()
{
String body;
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
body = await reader.ReadToEndAsync();
}
UserSignup user = JsonConvert.DeserializeObject<UserSignup>(body);
return user.email;
}
}
I was trying something like ([FromBody] UserSignup user) getting Mvc.SerializableError and "The input was not valid." Soon to be on https://github.com/Hover-Us/

Getting null value to controller's action passing from javascript using jquery

What I tried in my project is like passing checkbox's selected value as a comma separated string to json of my controller.. but i'm not getting a value to the json action.. it shows null over there.
How can I do this? Please help me
function getIds(checkList)
{
var idList = new Array();
var loopCounter = 0;
jQuery("input[name=" + checkList + "]:checked").each
(
function()
{
idList[loopCounter] = jQuery(this).val();
loopCounter += 1;
}
);
alert(idList);
jQuery.getJSON("/Photos/CheckForIdsJson", { idList: idList });
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CheckForIdsJson(Int32[] idList)
{
JsonResult result = new JsonResult();
result.Data = idList;
return result;
}
You can have a look at this post : AJAX Post of JavaScript String Array to JsonResult as List<string> Always Returns Null? or this one : Send list/array as parameter with jQuery getJson . It seems that you have to indicate traditional: true in your ajax call.
Use this in your script :
var did ='',
$("#tbl").find("input:checkbox").each(function (i) {
if (this.checked == true) {
did += $(this).val() + ",";
}
});
alert(did);
if (did == "") {
alert("Please Select");
return;
}

Categories

Resources