I am trying to send json to my mvc action controller, I searched and researched on the web, but I always receive the object in my controller with all "null" fieds.
I tryed to send a string instead then an object but same result, a null string.
I really don't know what could be wrong:
Class:
namespace TestUser.Models
{
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Sex { get; set; }
public string Transfer { get; set; }
public string PercTransf { get; set; }
}
}
Controller:
[HttpPost]
public ActionResult CheckUser( User dati)
{
if (dati != null)
{
if (string.IsNullOrEmpty(dati.Name))
return Json("Insert the name");
if (string.IsNullOrEmpty(dati.Surname))
return Json("Insert the surname");
if (dati.Sex != "m" && dati.Sex != "f")
return Json("Insert the sex");
return Json("OK");
}
else
{
return Json("No valid data");
}
}
Ajax:
function checkAndSaveData() {
var obj = new Object();
obj.Name = $("#nome").val();
obj.Surname = $("#cognome").val();
obj.Email = $("#email").val();
obj.Sex = $('#selectSesso').find(":selected").val();
obj.Transfer = "no";
obj.PercTransf = "0";
if ($('#trasferte:checked').val() == "on") {
obj.Transfer = "si";
obj.PercTransf = $("#tempotrasf").val();
};
$.ajax({
type: 'post',
dataType: 'json',
url: '#Url.Action("CheckUser")',
data: JSON.stringify({ obj }),
success: function (json) {
if (json == "ok") {
$.ajax({
type: 'post',
dataType: 'json',
url: "#Url.Action("Save")",
success: function (json) {
if (json == "ok") {
alert();
} else {
alert(json);
}
},
});
} else {
alert(json);
}
},
});
}
You don't seem to be sending the dataObject object in the ajax request.
Try:
data: { JSON.stringify(obj) }
Also, the object you pass in the data field of the ajax request doesn't need to be on a 'dati' property of an object.
MVC should figure out the rest!
I always use fiddler for debugging issues like this to check the json your sending in the http request is as you'd imagine :)
your class properties and javascript properties should be same, then your controller action parameter name should match with jason string. so use like this JSON.stringify({"dati": obj });
There were many edits in the question so I'm going to publish full code. This worked for me when testing.
Javascript code
var obj = new Object();
obj.name = "name";
obj.surname = "cognome";
obj.email = "email";
obj.sex = 'm';
obj.transfer = "no";
obj.perctrasf = "0";
$.ajax({
type: 'post',
contentType: 'application/json',
dataType: 'json',
url: '#Url.Action("CheckUser")',
data: JSON.stringify({ dati: obj }),
success: function (json) {
if (json == "ok") {
alert("ok");
} else {
alert(json);
}
},
});
Controller
[HttpPost]
public ActionResult CheckUser(User dati)
{
return Json(dati);
}
Model
public class User
{
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Sex { get; set; }
public string Transfer { get; set; }
public string PercTransf { get; set; }
}
Related
I'm using dapper to map my database with my mvc project, i have debugged my code to know what's going on and my ReceiveData method isn't receiving the data for some reason when it sends it to my GeoCreate it shows nothing, also i might me wrong because i placed my cursor on my Geo.RouteID, Geo.Latitude,etc and the data was there then it goes to my geography class and after that it's supposed to go to the if statement but it stops there, i'm sending json data with postman.
Here's my ReceiveData method
public bool ReceiveData(Geography Geo)
{
int GeoCreate = this.conn.Execute(#"INSERT GEOGRAPHY([ID_ROUTE],[LAT],[LONG],[BATTERY],[DateCreated],[DEVICE_ID]) values (#Lat,#Long,#Battery,#DateCreated,#Device_ID)",
new { RouteID = Geo.RouteID, Lat = Geo.Latitude, Long = Geo.Longitude, Battery = Geo.Battery, DateCreated = Geo.ObtainedDate, DeviceID = Geo.Device_ID });
if(GeoCreate > 0)
{
return true;
}
return false;
}
Here's the action for calling the ReceiveData method:
[Route("GeoCreate")]
[HttpPost]
public bool StoreLocation(Geography Geo)
{
return GD.ReceiveData(Geo);
}
Here's the javascript code that works for sending my data:
<script>
$(document).ready(function () {
var Geograph = {
Latitude: $("#Latitude").val(),
Longitude: $("#Longitude").val(),
Country: $("#Country").val(),
ObtainedDate: $("#ObtainedDate").val()
};
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.parse( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});
});
</script>
And my Geography class:
public class Geography
{
[Key]
public int RouteID { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public int Battery { get; set; }
public DateTime ObtainedDate { get; set; }
public int Device_ID { get; set; }
}
Here's the JSON data i'm sending:
{
"Latitude": 19.435547,
"Longitude": -81.77856,
"Battery": 100,
"ObtainedDate":"\/Date(1522600449000)\/",
"Device_ID": 1
}
I'm not setting the RouteID because it fills automatically in the database.
In your ajax call you should use JSON.stringify rather than parse method
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocation", "Home")',
dataType: 'json',
data: JSON.stringify( { Geo: Geograph }),
success: function (lctn) {
console.log(lctn);
debugger;
}
});
I can't seem to figure out how to get my Javascript object to bind to my model that is (as far as I can tell) just like it as far as properties go.
First the Javascript Object creation:
var transDetail = new Object();
transDetail.TransactionDetailID = transdetailId;
transDetail.TransactionID = "";
transDetail.Year = new Date().getFullYear();
transDetail.Volume = "";
transDetail.UnitPrice = "";
transDetail.TransferableVolume = "";
transDetail.Credits = "";
transDetail.Shares = "";
transDetail.DollarsPerShare = "";
It is then passed to this javascript function
function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
$.ajax(
{
url: '/TransactionDetail/LoadEditCreate',
data: JSON.stringify(transactionDetail),
dataType: 'json',
success: function (result) {
d.html(result);
CreateEditTransDetail(d, cb, title, transactionDetail);
d.dialog('open');
}
}
);
}
I've verified that the year property before transmission is filled with 2015.
Now the model definition
public partial class TransactionDetail
{
public int TransactionDetailID { get; set; }
public int TransactionID { get; set; }
public int Year { get; set; }
public Nullable<int> Volume { get; set; }
public Nullable<int> UnitPrice { get; set; }
public Nullable<int> TransferableVolume { get; set; }
public Nullable<int> Credits { get; set; }
public Nullable<int> Shares { get; set; }
public Nullable<int> DollarsPerShare { get; set; }
}
And the Action definition
public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)
When I break first thing into the action all non nullable ints are set to 0 and all nullable are set to null.
The problem is with sending the data: JSON...
You have 2 options:
use POST: (tried and works)
function loadTransDetailEditCreate(d, cb, title, transactionDetail) {
$.ajax(
{
type: 'post', //added
contentType: "application/json; charset=utf-8", //added
url: '/TransactionDetail/LoadEditCreate',
data: JSON.stringify(transactionDetail),
dataType: 'json',
success: function (result) {
d.html(result);
CreateEditTransDetail(d, cb, title, transactionDetail);
d.dialog('open');
}
}
);
}
and decorate your controller with [HttpPost] attribute
[HttpPost]
public PartialViewResult LoadEditCreate(TransactionDetail transactionDetail)
If you want to use get - look here (didn't try, should work)
I have to pass model and also another array list value from javascript to controller.
Javascript code
$("#SaveData").click(function (e) {
debugger
var formdata = $("form").serialize();
var list = new Array();
var postData;
$('input.chkevent').each(function () {
debugger
if (this.checked == true) {
var parent_id = this.parentElement;
var par2 = parent_id.previousElementSibling;
var par3 = par2.previousElementSibling;
var child = par3.childNodes[0];
var child_val = child.defaultValue;
var arr_date = this.parentElement.nextElementSibling.childNodes[0].value;
var dep_date = this.parentElement.nextElementSibling.nextElementSibling.childNodes[0].value;
var id = new Array(); ;
id.push(child_val, arr_date, dep_date);
list.push(id);
postData = {values: list };
}
});
$.ajax({
type: "POST",
url: "/umbraco/Surface/HomeSurface/FormData",
data: (formdata ? formdata + "&" : "") + "values=" + postData,
traditional: true,
success: function (data) {
//alert("ajax request to server succeed");
}
});
});
Only one kind of data I got, either postDataor formdata but I need both of them to pass in controller method as below:
public ActionResult FormData(PERSON_MASTER person, string[] values)
{}
PERSON_MASTER.cs
public class PERSON_MASTER
{
[Key]
public int PERSON_ID { get; set; }
public string ICARD_ID { get; set; }
[Required]
public string FNAME { get; set; }
[Required]
public string LNAME { get; set; }
public string GENDER { get; set; }
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
[Required]
public int? CITY_ID { get; set; }
public int? STATE_ID { get; set; }
[Required]
public int? COUNTRY_ID { get; set; }
public string CONTACT_NO { get; set; }
}
Thanks in advance.
Try this, not tested:
var model = {
person: $("form").serialize(),
values: list
};
$.ajax({
type: "POST",
url: "/umbraco/Surface/HomeSurface/FormData",
data: JSON.stringify(model),
traditional: true,
success: function (data) {
//alert("ajax request to server succeed");
}
});
Whenever i pass data to controller, i make sure that the parameter names coresponds with the parameter names in the controller:
$.ajax({
type: "POST",
url: "/umbraco/Surface/HomeSurface/FormData",
data: {
person: formdata,
values: list
},
traditional: true
});
Update: You must also make sure that the parameters has the same shape. In your code you are passing a multidimensional array to non-multidimensional array
Until now, I've been successfully passing an array of strings to my controller via AJAX using JSON.stringify.
However, now I need to move that array into another object in order to pass more data to the AJAX call.
The following (and many other attempts) result in the jobRequest.Tests having no members when passed to the controller:
function executeTests(testsToRun) {
if (testsToRun.length > 0) {
var jobRequest = new Object;
jobRequest.SampleTitle = '#ViewBag.SampleTitle';
jobRequest.SampleLanguage = '#ViewBag.SampleLanguage';
jobRequest.Mode = '#ViewBag.SampleMode';
jobRequest.Tests = JSON.stringify(testsToRun);
$.ajax({
url: '#Url.Action("ProcessJob", "ProcessJob")',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'jobRequest': jobRequest }),
success: function (jobId) {
window.location.href = '#Url.Action("Index", "ProcessJob")' + '?id=' + jobId;
}
});
}
}
public class JobRequest
{
public string SampleTitle { get; set; }
public string SampleLanguage { get; set; }
public string Mode { get; set; }
public List<string> Tests = new List<string>();
}
public JsonResult ProcessJob(JobRequest jobRequest)
{
...
You can change the class JobRequest like this:
public class JobRequest
{
public string SampleTitle { get; set; }
public string SampleLanguage { get; set; }
public string Mode { get; set; }
public List<string> Tests { get; set; }
}
and remove the JSON.stringify in the array:
jobRequest.Tests = testsToRun;
I'm new to javascript and MVC I'm working on a sample application containing a sign up page and I'm using ajax to done the process my current code is given below
function create() {
var user_name = $("#txtUser").val();
var pass = $("#txtPass").val();
var email = $("#txtEmail").val();
var phone = $("#txtPhone").val();
var city = $("#txtCity").val();
var state = $("#txtState").val();
var zip = $("#txtZip").val();
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data: { user_name: user_name, pass: pass,email:email,phone:phone,city:city,state:state,zip:zip },
success: function (response) {
alert("success");
}
});
return false;
}
and its working fine but I want to know that is there any way to pass these values as a single object like in C# forgive me if this question is too silly
serverside code
[HttpPost]
public ActionResult Create(User user)
{
UserDL newUser = new UserDL();
newUser.SignUp(user);
return Json(new { success = true });
}
and also I want to know is there any way to combine these values directly with my server side object
User.cs
public class User
{
public virtual int ID { get; set; }
public virtual string UserName { get; set; }
public virtual string Password { get; set; }
public virtual string EmailID { get; set; }
public virtual int Phone { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual int Zip { get; set; }
}
Try below code. Sore all variable in single object named data and pass it.
function create() {
var data = {
'UserName': $("#txtUser").val(),
'Password': $("#txtPass").val(),
'EmailID': $("#txtEmail").val(),
'Phone': $("#txtPhone").val(),
'City': $("#txtCity").val(),
'State': $("#txtState").val(),
'Zip': $("#txtZip").val()
};
$.ajax({
url: '/EmberNew/Home/Create',
type: 'POST',
data: data ,
success: function (response) {
alert("success");
}
});
return false;
}