Ajax Json calling MVC4 Controller Method Parameter Always Null - ajax

I am using Ajax with MVC4 web application. I've got a problem with passing values to action method. It's always pass the null as the parrameter value.
Here is my codes.
function onChange(arg) {
var adrId = $.map(this.select(), function (item)
{
return $(item).find('td').first().text();
});
GetEntries(adrId);//Calling the function
}
function GetEntries(adrId) {
//alert("AdrId >> "+adrId); here it shows value is 3465
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: adrId }),
success: function (result) {
alert("success");
}
});
}
[HttpPost]
public JsonResult LoadCustomer(string adrId)//HERE value is ALLWAYS NULL.. :(
{
Address_SelectW adrList = new Address_SelectW();
adrList = this.commonObj.CustomersSelectByAdrKy(cky, usrKy, AdrKy);
return Json(adrList, JsonRequestBehavior.AllowGet);
}
Please help me to solve this problem. Thank you.. :)
===========================================================================
Additional Informations....
I have used another one to insert data. it's worked fine..
$("#btnSave").click(function () {
//var ContactID = $("#txtContactId").val();
var Company = $("#txtCompany").val();
var Status = $("#cmbStatus").val();
var IsActive = $("#IsActive").is(':checked');
var Comments = $("#txaComments").val();
var Country = $("#cmbCountry").val();
var Address1 = $("#txtAddress1").val();
//var Address2 = $("#txtAddress2").val();
var City = $("#txtCity").val();
var State = $("#txtState").val();
var PostalCode = $("#txtPostalCode").val();
var VatNo = $("#txtVatNo").val();
var RegNo = $("#txtRegNo").val();
var Phone = $("#txtPhone").val();
var Email = $("#txtEmail").val();
var AdrKey = $("#AdrID").val();
$.ajax({
url: "Customer/InsertCustomer",
data: {
//'ContactID': ContactID,
'Company': Company,
'Status': Status,
'IsActive': IsActive,
'Comments': Comments,
'Country': Country,
'Address1': Address1,
//'Address2': Address2,
'City': City,
'State': State,
'PostalCode': PostalCode,
'VatNo': VatNo,
'RegNo': RegNo,
'Phone': Phone,
'Email': Email
},
dataType: "json",
type: 'POST',
success: function (data) {
alert("Successfully Inserted!");
},
error: function () {
alert("error");
}
});
});
[HttpPost]
public ActionResult InsertCustomer(string Company, int Status, bool IsActive, string Comments, int Country, string Address1, string City, string State, string PostalCode, string VatNo, string RegNo, string Phone, string Email)
{
AdrCustomModel model = new AdrCustomModel();
bool process = false;
model.Company = Company;
model.Status = Status;
model.IsActive = IsActive;
model.Comments = Comments;
model.Country = Country;
model.Address1 = Address1;
model.City = City;
model.State = State;
model.PostalCode = PostalCode;
model.VatNo = VatNo;
model.Phone = Phone;
model.RegNo = RegNo;
model.Email = Email;
model.cky = cky;
model.ContactID = this.CustomerID(Status);
process = this.commonObj.InsertAdrCustomer(model,usrKy);
Accounts_Select accmodel = new Accounts_Select();
accmodel.CKy = cky;
accmodel.AccCd = model.ContactID;
accmodel.AccNm = Company;
accmodel.AccTypKy = this.commonObj.AccTypeKyByPrefixKy(Status);
process = this.commonObj.InsertAccount(accmodel, usrKy);
return Json(process, JsonRequestBehavior.AllowGet);
}
I have no idea about why this one is working fine and that one is not working. I have tried both JsonResult and ActionResult to Action method. And also tried with and without [HttpPost].
But always Parrameter value is NULL

I'm not sure if it will solve your problem but you can try this.
Place [WebMethod] attribute in your controller method.
or you can you can pass url with appended id like
'Customer/LoadCustomer'+ adrId

Put the property name in quotes:
data: JSON.stringify({ 'adrId': adrId }),

In your first example, you send a JSON object, in the second you just post data.
JSON is unnecessarily complicated to send just one value. Try this instead:
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
data: {'adrId': adrId },
dataType: 'json',
success: function (result) {
alert("success");
}
});

It required concatenate "" with the parameter which you wanna pass to Action method.
function GetEntries(adrId) {
var NewAdrId = ""+adrId; //<<<<<<<<<<<< Answer<<<<<<<<<<<<<<
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: NewAdrId }),
success: function (result) {
alert("success");
}
});
}
// Thanks :)

Related

Ajax post zero to controller

I'm trying to POST an int with Ajax to my controller
Js
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: { id: provinceId },
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
code in my controller :
[HttpPost]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == 5);
return Json(cities);
}
but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0
You should create an class that have a Id Property.
public class ProvinceIdDto
{
public int Id { get; set; }
}
replace int id with ProvinceIdDto model in action
[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
var cities = _context.City.Where(c => c.ProvinceId == model.Id);
return Json(cities);
}
replace { id: provinceId } with JSON.stringify({ Id: provinceId }),
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity",
type: "POST",
data: JSON.stringify({ Id: provinceId }),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
Another options is you can replace HttpPost method with HttpGet and pass id to action like this.
Change type: "POST", to type: "GET",
<script>
function FillCity() {
var provinceId = $(provinces).val();
$.ajax({
url: "FillCity?id="+provinceId,//<-- NOTE THIS
type: "GET",//<-- NOTE THIS
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#cities").html(""); // clear before appending new list
$.each(data, function (i, city) {
$("#cities").append(
$('<option></option>').val(city.Id).html(city.Name));
});
}
});
}
</script>
C#
[HttpGet]
public ActionResult FillCity(int id)
{
var cities = _context.City.Where(c => c.ProvinceId == id);
return Json(cities);
}
when you do { id: provinceId } you are creating an object with property id
in your controller you are just expecting an id. You will need to ether:
A pass it as a query parameter url: "FillCity?id=" + provinceId
B create an object to be parsed from the request body.
public class Payload {
public int Id {get;set;}
}
and use it like this
public ActionResult FillCity([FromBody] Payload payload)
Can you verify this statement has a value:
var provinceId = $(provinces).val();
It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".
You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I think it might not be finding the input field successfully.

Failed to call action method using Ajax

Here's my JS (jQuery and Ajax) code:
$('#submitSignUp').click(function () {
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify({ name: name, email: email, password: password }),
success: function () {
alert("Rgistered.");
}
})
})
and this is my action method. (It's in "Home controller"):
[HttpPost]
public JsonResult SignUp(string name, string email, string password)
{
TodoNet.Models.TodonetModel database = new TodoNet.Models.TodonetModel();
TodoNet.Models.User oUser = new TodoNet.Models.User()
{
FirstName = name,
LastName = name,
Email = email,
Password = password,
Salt = password,
IsDeleted = false,
IsOnline = false,
PhoneNumber = "09212131212",
RegisterDate = DateTime.Now,
LastLoginDate = DateTime.Now
};
database.Users.Add(oUser);
database.SaveChanges();
return new JsonResult();
}
but I don't know why it doesn't work. after clicking on the '#signUpSubmit' button, the "alert("Registered.")" will not be shown.
What am I doing wrong??
Note: without using Ajax, (by using ordinary send form data to the action method, everything works properly (It means I know that there's nothing wrong with the back-end code)
If the form submitting normally works, then your ajax should be sending form data not json.
Also, prevent the default action of the button click.
$('#submitSignUp').click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: "json",
data: $("#the_form_id").serialize(),
success: function () {
alert("Rgistered.");
}
});
});
You can also do this way.
On your submitSignUp submit your parameter as following.
var param =
{
name: $('#name').val(),
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: '#Url.Action("SignUp")',
type: "POST",
dataType: 'json',
data: JSON.stringify(param),
async: false,
cache: false,
traditional: true,
contentType: 'application/json',
success: function (data) {
alert(1)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
Change your controller:
[HttpPost]
public ActionResult SignUp(string name, string email, string password)
{
//other implementation
return Json("", JsonRequestBehavior.AllowGet);
}
Hope this helps!
Try this as your ajax method -
$('#buttonID').on("click",function() {
var data=
{
var name = $('#name').val();
var email = $('#email').val();
var password = $('#password').val();
};
$.ajax({
url: '#Url.Action("SignUp","ControllerName")',
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(data),
success: function () {
alert("success");
}
});
});

ajax call sending null value to controller

my model:
public class Hello
{
public List<string> name;
public List<string> phone;
public List<string> contact;
}
my controller code is
public ActionResult Home(Hello obj) // obj is coming out to be null
{
}
my script is
var names =[];
var phones =[];
var contacts = [];
// some code to fill the arrays
var obj = [{
name: names,
phone: phones,
contact: contacts,
}];
debugger;
$.ajax({
cache: false,
url: 'Home',
data: { obj:obj },
success: function (data) {
var response = JSON.parse(data);
window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
i can see in the debugger that data is stored in the arrays but when i am sending data to controller the obj is null can someone suggests where am i going wrong ?
You have object in code behind so do not pass array of Hello object.
And also use POST request because GET request have not message body.
Please use below
var obj = {
name: ['1', '2', '3'],
phone: ['234324', '34343243', '3434234234'],
contact: ['Test1', 'Test2', 'Test3']
};
debugger;
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Home',
data:JSON.stringify({ obj: obj }),
success: function (data) {
var response = JSON.parse(data);
// window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
public class Hello
{
public List<string> name { get; set; }
public List<string> phone { get; set; }
public List<string> contact { get; set; }
}
Actually i solved the problem , i had to set
traditional:true,
in my ajax call

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

How to send a parameter to controller method with javascript in MVC3?

How can I send parameter from javascript to controller method ? For example I 'm trying to send parameter "2012"
Here is my script in my View:
$.ajax({
type: "get", url: "test", data: {}, // How can i fill this data like #item ?
success: function (data) {
alert(data);
}
my controller method:
public string test()
{
TestServices client = new TestServices();
client.ClientCredentials.UserName.UserName = "service_test";
client.ClientCredentials.UserName.Password = "..";
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
decimal? x = client.GetTest(2012, 7, 1);
return (""+x);
}
[HttpGet]
public string test(string name, string age)
And the ajax
$.ajax({
type: "get", url: "test", data: {name:"Messi",age:"36yo"}, // How can `i fill this data like #item ?`
success: function (data) {
alert(data);
}

Resources