Ajax not hitting controller method - c#

I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.

Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});

The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});

Change the url to this:
url: "../Client/ShowClient"

Related

Web API is not working when calling through C# or jQuery ajax

Going crazy. The first call sets the session and the 2nd call gets the session. First 'Post' call return username and session id correctly but when I try to get the session, it returns blank with status code 200.
The same is the case with HttpClient (C#) code.
Both the call works perfectly if I try to set through browser or PostMan.
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session?username=xxxx&password=xxxx",
type: 'POST',
dataType: 'application/json',
success: function (result) {
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session",
type: 'Get',
dataType: 'application/json',
crossDomain: true,
success: function (result) {
debugger;
},
error: function (result) {
debugger;
}
});
},
error: function (result) {
debugger;
$.ajax({
url: "http://localhost:xxxx/xxxx/api/v1/session",
type: 'Get',
dataType: 'application/json',
crossDomain: true,
success: function (result) {
debugger
},
error: function (result) {
debugger;
}
});
}
});
The Get Request from Post Man
{"sessionId":"088BE3296B8778948F649A6B7B8C064B","userName":"user1"}
Am I missing anything?
Do note that Web-APIs are exposed by third party.
The problem is you have used the post method and trying to pass the data in query string.
function DoLogin() {
if (document.getElementById("Email").value == "" && document.getElementById("Password").value == "") {
document.getElementById("Email").focus();
toastr.error("Please enter email and password.");
}
else if (document.getElementById("Email").value == "") {
document.getElementById("Email").focus();
toastr.error("Please enter valid email address.");
}
else if (document.getElementById("Password").value == "") {
document.getElementById("Password").focus();
toastr.error("Please enter valid password.");
}
else {
document.getElementById("ButtonLogin").value = "Validating your account...";
document.getElementById("ButtonLogin").disabled = true;
var model = {
Email: $('#Email').val(),
Password: $('#Password').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "#Url.Action("Login", "Account", null)",
contentType: "application/json"
}).success(function (res) {
var Type = res.type;
if (Type == "error") {
toastr.error(res.value);
document.getElementById("ButtonLogin").value = "login";
document.getElementById("ButtonLogin").disabled = false;
}
else {
window.location.href = res.returnUrl;
}
});
}
}
Usually, in the response for the POST request, there will be a Set-Cookie header.
You may need to pass the cookie in the GET request.

function is taking Null value by ajax in mvc5

This ajax is calling from .cshtml file to controller but getValue function is taking Null value on load, but afterwards it works fine. It evens shows the value on alert on ajax call, but getting null on controller. Any help would be highly appreciated.
<script>
$(document).ready(function(){
//get value from dropdown list
var ID = $('#cmb').val();
// ID is taking value
$.ajax({
// /ControllerName/FunctionName
// /Home/getvalue
url: "/Home/getValue",
type: "POST",
// ID is getting from dropdownList
// parameterName/value
data: JSON.stringify({'_ID':ID}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
</script>
[HttpPost]
public JsonResult getValue(string _ID)
{
string a = _ID;
}
It is reasonable that you are taking null on the load, since the value of HTML element with id cmd would be undefined, since I assume that there isn't any value that is selected (option of a select element has an attribute called selected, when you have selected a value this attribute has the value true).
The strange thing is that you say that afterwards works as it is expected. I doubt this, except if you have any other code that you haven't include it in your post. As it seems there is only an AJAX call after the successfull load of the DOM.
Usually we register to an event, when we make an AJAX call like this. I could assume that you could register to the onChange event of the value of select element (dropdown)
$(document).ready(function(){
$("#cmb").on("change", function(){
//get value from dropdown list
var ID = $(this).val();
// ID is taking value
$.ajax({
// /ControllerName/FunctionName
// /Home/getvalue
url: "/Home/getValue",
type: "POST",
// ID is getting from dropdownList
// parameterName/value
data: JSON.stringify({'_ID':ID}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
});
You have to change your URL and parameter check below code for that :
$(document).ready(function(){
//get value from dropdown list
var ID = $('#cmb').val();
// ID is taking value
$.ajax({
url: "/Home/getValue?_ID=" + ID,
type: "POST",
dataType: "json",
data: 'json',
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
Cheers !!
Change Paramaters Name
use id in replace of _ID
[HttpPost]
public JsonResult getValue(string id)
{
string a = id;
}
$(document).ready(function(){
$("#cmb").on("change", function(){
//get value from dropdown list
var id= $(this).val();
// ID is taking value
$.ajax({
// /ControllerName/FunctionName
// /Home/getvalue
url: "/Home/getValue",
type: "POST",
// ID is getting from dropdownList
// parameterName/value
data: JSON.stringify({'id':ID}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});
});
if you are sure that your ID is not null then just try this.
<script>
$(document).ready(function(){
var ID = $('#cmb').val();
$.ajax({
url: "/Home/getValue",
type: "POST",
data: {_ID:ID},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "success") {
//if got response
//alert(data.status);
}
},
error: function () {
//if if not response
//alert('something went wrong');
}
});
});

Pass array to Controller Action via AJAX

I saw similar questions, but none helps me.
I have the simplest code:
public JsonResult JsonGetStatesInfo(object[] instructions)
{
if (Request.IsAjaxRequest())
{
return Json(String.Empty);
}
else
throw new NoAjaxRequestException();
}
and client side:
var instructions = [];
instructions.push('abc');
instructions.push('ddd');
instructions.push('assdbc');
var inst = JSON.stringify(instructions);
$.ajax({
cache: false,
data: { 'instructions': inst },
traditional: true,
dataType: 'json',
url: '/State/JsonGetStatesInfo',
type: 'post',
success: function (resp) {
},
error: function (data) {
alert(data.error);
}
});
On client side I tried with JSON.stringify, without JSON.stringify, with traditional: true, without traditional: true
On server side I tried as parameter : object[], object, List< object >, List< string >, IEnumerable< string > etc
Nothing worked! How to do it correctly?
SOLVED:
My problem was trivial - one from real values of array had HTML Tag. Just need add [ValidateInput(false)] to action method
You just need the following settings:
Pass array of string to a MVC Action by Ajax:
Controller:
public JsonResult MyAction(string[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': ['abc', 'dcs', 'arr'] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'post',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
Using contentType: "application/json; charset=utf-8" is recommended too.
Pass array of int to a MVC Action by Ajax:
Also I use bellow codes to path an array of int to an Action
Controller:
public JsonResult MyAction(int[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': [1, 2, 3] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'get',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
public ActionResult JsonGetStatesInfo(string[] instructions)
{
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = instructions.Length}
};
}
Client side
var instructions = ['abc', 'dcs', 'arr'];
$.post('/State/JsonGetStatesInfo', { instructions: instructions },
function (data) {
if (data.result!= null && data.result!= undefined) {
alert(data.result);
}
});
Try this...
At least, you can pass javascript array as a string and deserialize it in the controller
public JsonResult JsonGetStatesInfo(string instructions)
var instructionsArray= JsonConvert.DeserializeObject<string[]>(instructions);
Or use new Array like explained here : https://stackoverflow.com/a/310136/3063094
Try adding:
contentType: "application/json; charset=utf-8"
To you AJAX call, And please delete the:
JSON.stringify(instructions);
Because you are trying to stringify an object, which will be sent to the server as a string rather than an object (and the server side expects an object).
you can also delete the
traditional: true,
ache: false,

Pass Strongly Typed data and JSON string to controller from $.ajax funtion in View

I have ASP.NET-MVC5 application. I have strongly typed form and I successfully can pass back to controller. Now I have JavaScript array variable that I need to also send so I need to post back both information from view to controller using .$ajax post function.
I have update code as to add avaScript array variable, since then I am getting null value for form data.
View
var AdditionalTenentList = {
StudentUWLID: []
};
$('#CreateStudentRentingApplicationForm').submit(function (e) {
e.preventDefault();
var AdditionalTenentJsonList = JSON.stringify(AdditionalTenentList);
alert(AdditionalTenentJsonList);
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: { ApplicationModelData: $(this).serialize(), TenentJSONList: AdditionalTenentJsonList },
}).done(function (data, textStatus, jqXHR) {
//// my other code here.....
}
</script>
In another function thats how I am pushing value to array
AdditionalTenentList.StudentUWLID.push(StudentUWLID);
Controller
[Authorize]
[HttpPost]
public ActionResult ApplyForAccommodation(AccommodationApplicationViewModel ApplicationModelData, string TenentJSONList)
{
return null;
}
with the following code I get header response as
$.ajax({
url: formURL,
type: "POST",
dataType:"JSON",
data: JSON.stringify({ TenentJSONList: AdditionalTenentList }),
}).done(function (data, textStatus, jqXHR) {
..........
public ActionResult ApplyForAccommodation(string [] TenentJSONList)
{
var a = "d";
return null;
}
I have found the answer as following;
var AdditionalTenentList = new Array();
$('#CreateStudentRentingApplicationForm').submit(function (e) {
e.preventDefault();
var formURL = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
url: formURL,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ TenentJSONList: AdditionalTenentList, ApplicationModelData: $("#CreateStudentRentingApplicationForm").serializeObject() }),
}).done(function (data, textStatus, jqXHR) {
// .........my rest of code
...
[Authorize]
[HttpPost]
public ActionResult ApplyForAccommodation(string[] TenentJSONList, AccommodationApplicationViewModel ApplicationModelData)
{

Passing JSON to WebApi in MVC5

im facing issues in syntax to pass json array from jquery to the webapi in my mvc5 project .
Following is my code :-
C# code:-
//GET Instance
// GET: api/PostDatas
public IQueryable<PostData> GetPostDatas()
{
return db.PostDatas;
}
//POST Instance
// POST: api/PostDatas
[ResponseType(typeof(PostData))]
public IHttpActionResult PostPostData(PostData postData)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.PostDatas.Add(postData);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = postData.postDataID }, postData);
}
JQuery
<script>
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: model,
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
</script>
Im not able to send the data using jquery to my c# controller , just need to understand the syntax . Thank you .
check following things in your code:
1) Method attribute [HttpPost]
2) [FromBody] for input model
3) Check PostData class, it should contain public properties for userid, Description and photoid with case-sensitive of variable names.
and mainly change your AJAX request code to:
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: JSON.stringify(model), //i have added JSON.stringify here
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
Please let me know, is this works for you?
I included [FromBody] in the parameter in my previous project.
Something like this:
[HttpPost]
public IHttpActionResult Register([FromBody]PostData postData)
{
// some codes here
}
I was able to read the JSON data from that notation.

Categories