I am sending post method to server but receiving get method - javascript

I am working on .net core 3.1 api
I got error when calling api. Server responce 405
jquery.min.js:2 GET https://localhost:44345/api/Home/AddUpdateUser?callback=jQuery351026836393378483203_1613635815143&name=Ahsan&email=ahsan%40gmail.com&password=asdsdasda&_=1613635815145 net::ERR_ABORTED 405
This is my api controller class
public class HomeController : ControllerBase
{
private IRegisterUser _user;
private IMapper _mapper;
public HomeController(IRegisterUser user, IMapper mapper)
{
_user = user;
_mapper = mapper;
}
//api/Home
[HttpGet]
public IActionResult GetAllUser()
{
var users = _user.GetAllUser();
if (users != null)
{
var userVm = _mapper.Map<List<RegisterUserVm>>(users);
return Ok(userVm);
}
return Ok("Some error occured");
}
//api/Home
[HttpPost]
[Route("[action]")]
[Route("api/Home/AddUpdateUser")]
public IActionResult AddUpdateUser([FromBody] RegisterUserVm userVm)
{
//userVm.MacAddress = GetMacAddress();
var user = _mapper.Map<User>(userVm);
var msg = _user.AddUser(user);
string[] message = { "200", "testing" };
return Ok(message);
}
//api/Home/{id}
[HttpDelete]
public IActionResult DeleteUser(Guid Id)
{
var msg = _user.DeleteUser(Id);
return Ok(msg);
}
[HttpGet]
[Route("[action]")]
[Route("api/Home/GetUserById")]
public IActionResult GetUserById(Guid Id)
{
var user = _user.GetUserById(Id);
var userVm = _mapper.Map<RegisterUserVm>(user);
if (userVm != null)
return Ok(userVm);
return Ok("Some error occured");
}
}
Here is my ajax call
<script>
$("#button").click(function (e) {
e.preventDefault()
var data = {
name: "Ahsan",
email: "ahsan#gmail.com",
password: "asdsdasda"
};
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://localhost:44345/api/Home/AddUpdateUser",
data: data,
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger;
alert('ok');
},
error: function (result) {
debugger;
alert('error');
}
});
});
</script>

Change your ajax to this:
$.ajax({
url: "https://localhost:44345/api/Home/AddUpdateUser",
data: data,
success: function (result) {
debugger;
alert('ok');
},
error: function (result) {
debugger;
alert('error');
}
});
and remove [post] from your action header and fix the route:
[Route("~/api/Home/AddUpdateUser")]
public IActionResult AddUpdateUser([FromBody] RegisterUserVm userVm)
{
....
}
And you will have to resolve CORS issue by adding to startup this code:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowAnyOrigins", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseCors("AllowAnyOrigins");
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
````

Related

jquery ui autocomplete Uncaught TypeError: Cannot read property '0' of undefined

I have this error as displayed in the console:
jquery-3.3.1.js:7972 Uncaught TypeError: Cannot read property '0' of undefined
at val (jquery-3.3.1.js:7972)
at add (jquery-3.3.1.js:8463)
at buildParams (jquery-3.3.1.js:8450)
at Function.jQuery.param (jquery-3.3.1.js:8483)
at Function.ajax (jquery-3.3.1.js:9073)
at $.<computed>.<computed>.source (Index:189353)
at $.<computed>.<computed>._search (VM12 jquery-ui-1.12.1.js:6015)
at $.<computed>.<computed>._search (VM12 jquery-ui-1.12.1.js:144)
at $.<computed>.<computed>.search (VM12 jquery-ui-1.12.1.js:6007)
at $.<computed>.<computed>.search (VM12 jquery-ui-1.12.1.js:144)
and it is sent when I start typing.
my script is
$('#pesticideTypeInput').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetPesticideTypesList", "Search")',
dataType: "json",
data: { search: $('#pesticideTypeInput').val },
success: function (data) {
response($.map(data, function (item) {
//return { label: item.PesticideTypeAR, value: item.PesticideTypeAR };
return item;
}));
},
error: function (xhr, status, error) {
alert("Error");
}
});
}
});
in my controller I have:
public JsonResult GetPesticideTypesList(string term)
{
var pesticidesTypesList = db.PesticideTypes.Where(x => x.PesticideTypeAR.Contains(term)).ToList();
return new JsonResult {Data=pesticidesTypesList, JsonRequestBehavior=JsonRequestBehavior.AllowGet };
}
My model class is:
public partial class PesticideType
{
public PesticideType()
{
this.PesticidesInfoes = new HashSet<PesticidesInfo>();
}
public int PesticideTypePk { get; set; }
public string PesticideTypeAR { get; set; }
public virtual ICollection<PesticidesInfo> PesticidesInfoes { get; set; }
}
I appreciate any help, thanks!

Asp.Net core MVC Javascript Ajax parameters null HttpPost

I am writing a javascript function for a button
<button type="button" class="btn btn-sm btn-outline-secondary" id="stopProcess" onclick="stopProcess(event, #queue.AgentQueueId, #queue.AgentId)" data-toggle="tooltip">Stop</button>
This is what my javascript function looks like
<script type="text/javascript">
$(document).ready(function () {
setInterval(function () {
reloadPage()
}, 50000);
});
function reloadPage() {
window.location.reload(true);
}
function stopProcess(e, agentQueueId, agentId) {
e.stopPropagation();
var data = JSON.stringify({ 'agentQueueId': agentQueueId, 'agentId': agentId });
$.ajax({
type: "POST",
url: "#Url.Action("StopTest", "Agents")",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
reloadPage();
},
error: function (data) {
$(".alert").text("Error completing the request.");
$(".alert").prop("hidden", false);
}
});
};
</script>
It correctly navigates to the function StopTest in my Agents controller but the parameters passed to it are null.
My controller code is
[HttpPost]
public bool StopTest(long agentQueueId, long agentId)
{
StopTestsResponse response = new StopTestsResponse();
try
{
response = _testAgentRepository.StopTest(new StopTestsRequest()
{
AgentId = agentId,
AgentQueueId = agentQueueId
});
}
catch (Exception ex)
{
throw ex;
}
return response.Success;
}
It would be of great help if anyone could point out where I am going wrong.
You should create a class with two properties:
public class Test
{
public long AgentQueueId { get; set; }
public long AgentId { get; set; }
}
And then in your controller you should have action signature like this:
public bool StopTest([FromBody]Test data)
You can see more about model binding in asp.net core here:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1

deserialize object when ajax call asmx web service

I have AJAX call where call web service. web service is should return value (token as a string). I tried my web service and try to invoke manually, it successfully retrieve the token as string. but, when I combine with AJAX call, it returns an object. How I can retrieve the value of the token?
here is my AJAX snippet
$.ajax({
url: "http://10.23.64.43:8035/iFrameIntegration.asmx/getToken",
data: JSON.stringify({ Token: { userName: 'crm' } }),
contentType: "application/json; charset=utf-8",
type: 'POST',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Error");
}
});
and here is my web service (ASMX)
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getToken()
{
var request = (HttpWebRequest)WebRequest.Create("http://10.23.64.37:8080/ACCMWS/member/SSOInit");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers["userId"] = "Svc_CRM";
request.Headers["loginType"] = "Internal";
request.Headers["token"] = "54a93982adf51adfb81885ddbbb1874e271605ce";
string result = string.Empty;
try
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{ \"userName\": \"crm\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = request.GetResponse() as HttpWebResponse)
{
if (request.HaveResponse && response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var resultTokenAwal = reader.ReadToEnd();
var resultToken = JsonConvert.DeserializeObject<RetrieveSSOTokenResult>(resultTokenAwal);
result = resultToken.data.ssotokenList[0].ssoToken;
}
}
}
}
catch (WebException e)
{
if (e.Response != null)
{
using (var errorResponse = (HttpWebResponse)e.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
result = error;
}
}
}
}
}
catch(Exception ex)
{
ex.Message.ToString();
}
return result;
}
and here is my class from my web service
public class RetrieveSSOTokenResult
{
public string status { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
public class Data
{
public Ssotokenlist[] ssotokenList { get; set; }
}
public class Ssotokenlist
{
public string loginType { get; set; }
public string userName { get; set; }
public string userId { get; set; }
public string ssoToken { get; set; }
public long expiryTime { get; set; }
}
here is the result that I get when call from AJAX
{"d":"f0d7ef7e29b89d42e84d6590b8e7b52f899f3b7a"}
please advise, I only want to alert the value of the token, which is f0d7ef7e29b89d42e84d6590b8e7b52f899f3b7a.
in the asmx, when I try to invoke, I only got this information
var from resultTokenAwal is this
{"d":"status":"success","message":"","data":{"ssotokenList":[{"loginType":"Internal","userName":"CRM","userId":"E512E6D2-1584-4597-BBD6-01C724496107","ssoToken":"2f3b28def21bdace7bd7baacd0cd0bf72fbcb30b","expiryTime":1548047778532}]}}
but, in my asmx, the result of resultTokenAwal is this
{"status":"success","message":"","data":{"ssotokenList":[{"loginType":"Internal","userName":"CRM","userId":"E512E6D2-1584-4597-BBD6-01C724496107","ssoToken":"2f3b28def21bdace7bd7baacd0cd0bf72fbcb30b","expiryTime":1548047778532}]}}
UPDATE:
the data actually already parse in JSON in AJAX. so, just call the d. here is the update of AJAX.
$.ajax({
url: "http://10.23.64.43:8035/iFrameIntegration.asmx/getToken",
data: JSON.stringify({ Token: { userName: 'crm' } }),
contentType: "application/json; charset=utf-8",
type: 'POST',
success: function (data) {
alert(data.d);
},
error: function (data) {
alert("Error");
}
});

Getting Null object array jquery post

I am new to Angular.js framework. I am getting data which i am further assigning to array using angular scope.
Modal.CS:
public class AppSetting1
{
public int lng_AppSettings { get; set; }
public string str_SettingName { get; set; }
public string str_SettingValue { get; set; }
public string str_Type { get; set; }
public AppSetting1(int _lng_AppSettings, string _str_SettingName, string _str_SettingValue, string _str_Type)
{
lng_AppSettings = _lng_AppSettings;
str_SettingName = _str_SettingName;
str_SettingValue = _str_SettingValue;
str_Type = _str_Type;
}
}
internal string GetAppSettings()
{
try
{
List<AppSetting1> objAppsettings = new List<AppSetting1>();
objAppsettings.Add(new AppSetting1(1,"Name1","Value1","Type"));
objAppsettings.Add(new AppSetting1(2, "Name2", "Value2", "Type2"));
return JsonConvert.SerializeObject(objAppsettings, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
}
catch (Exception ex)
{
throw ex;
}
}
Controller.CS:
[AuthCheckService, SessionCheckService]
[HandleModelStateException]
public string GetAppSettings()
{
try
{
ManageAppSettings accExec = new ManageAppSettings();
return accExec.GetAppSettings();
}
catch (Exception ex)
{
throw new ModelStateException(ex.Message, ex.InnerException);
}
}
[HttpPost]
public JsonResult SaveSettings(List<AppSetting1> AppSetting)
{
try
{
ManageAppSettings accExec = new ManageAppSettings();
return Json(AppSetting, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw new ModelStateException(ex.Message, ex.InnerException);
}
}
Angular.js:
(function () {
var app = angular.module('myAppSeetings', []);
app.controller('AppSettingsController', function ($scope) {
$scope.items = [];
$scope.SaveSettings = function () {
if (validate()) {
var token = $('[name=__RequestVerificationToken]').val();
var test = $scope.items;
$.ajax({
beforesend: showProgress(),
type: 'POST',
headers: { "__RequestVerificationToken": token },
url: getAppPath() + 'AppSettings/SaveSettings',
dataType: 'json',
data: { AppSetting: $scope.items },
success: function (result) {
if (result != "") {
//ShowSaveMessage(result);
//fetchData();
//$('#EditPopUp').css('display', 'none');
//$('#exposeMaskManageUser').css('display', 'none');
//clearForm();
}
else
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
},
complete: hideProgress,
error: function (ex) {
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
}
});
}
else {
ShowWarningMessage('Required fields must be completed prior to completing the work');
}
};
function fetchData() {
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
beforesend: showProgress(),
type: 'GET',
headers: { "__RequestVerificationToken": token },
url: getAppPath() + 'AppSettings/GetAppSettings',
dataType: 'json',
success: function (data) {
// console.log(data);
$scope.items = data;
$scope.$apply();
console.log($scope.items);
},
complete: hideProgress,
error: function (ex) {
ShowErrorPopup('An error has occurred. Please contact System Administrator.');
}
});
};
function validate() {
var val = true;
if ($("input").val().trim() == "") {
val = false;
}
return val;
}
fetchData();
});
})();
Problem:
On save click i am getting null on server side. Where i am going wrong here?
Try adding
contentType: 'application/json; charset=utf-8',
See this answer
Your code wrong here:
data: { AppSetting: $scope.items }
It should be
data: $scope.items
In your saveClick function: $scope.items now is []. It should have some values as you expect. Depend on your case it is from client or a default value for testing:
$scope.items = [{lng_AppSettings: 1, str_SettingName : 'Name 1'},
{lng_AppSettings: 2, str_SettingName : 'Name 2'}];

Calling controller with ajax in mvc

I'm trying to fetch data from a controller and update my view using ajax.
This is my controller:
public class PatientController
{
DatabaseContext db = new DatabaseContext();
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.FirstOrDefault(p => p.Cpr == "2410911615");
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And this is my ajax call:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
dataType: 'json',
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
When i call the function i always get the error alert.
GET http://localhost:51140/Patient/GetPatientFromCpr 404 (Not Found)
Can someone point out what's wrong?
(EDIT)
I now get a new error after adding ": Controller"
GET http://localhost:51140/Patient/GetPatientFromCpr 500 (Internal Server Error)
Your 'PatientController' is not a Controller (it does not inherit from Controller)
public class PatientController : Controller
{
....
}
Inherit you PatientController with Base Controller Class
public class PatientController : Controller
In controller
public JsonResult GetPatientFromCpr()
{
var patient = db.Patients.where(p => p.Cpr == "2410911615").FirstOrDefault();
return new JsonResult() { Data = patient, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And Specify the type of ajax calling
type: "POST" or type: "GET" ....
This will help you to fix error
Try using this, may be this works..!!
View:
function getPatient() {
cpr2 = $("#cpr-first").val() + $("#cpr-last").val();
$.ajax(
{
url: '/Patient/GetPatientFromCpr',
//dataType: 'json',
type:"POST", // GET or POST
success: function () {
alert("success");
},
error: function () {
alert("error");
},
});
}
Controller:
public class PatientController : Controller
{
....
}

Categories

Resources