My insert method isn't working - javascript

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;
}
});

Related

Get json data from ajax,process it,return answer

I have some troubles with transfer json data.
I have some dynamic page. I collect data to json object "Filters".
var Filters = { daterange: $('#daterange').val(), shop: val_shop, pr: val_pr, plan: val_plan, TabsList: TabsList }
$.ajax({
url: "/Reports/Report_2",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(
Filters
)
});
I try get it with JObject.
public IActionResult Report_2() //main Action
{
return View();
}
[HttpPost]
public async Task<IActionResult> Report_2([FromBody]JObject jsonResult)//catch json object
{
//do something
return View(_context.MyDatabase.Result);//return data from database for table(Razor Page)
}
I get Error 415. =(
If I try don't overload Report_2 Action().
$.ajax({
url: "/Reports/Report_2_Filter",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(
Filters
)
});
[HttpPost]
public async Task<JObject> Report_2_Filter([FromBody]JObject jsonResult)
{
return jsonResult;
}
I don't know how return result on Report_2 page. I need result on Report_2 Action becouse I must fill table on Report_2 page. I'm newbee in web, so I will be greateful for any help.
May be you need write ("");
var Filters = { "daterange": $('#daterange').val(), "shop": val_shop, "pr": val_pr, "plan": val_plan, "TabsList": TabsList }
You can add a function to be executed on success. Try to add the following to your ajax request:
success: function(data){
// Do something here
}
Have a look here to see the ajax events.
My solution:
I create class which stores variables:
public class FilterModel
{
public string var1{ get; set; }
public string var2{ get; set; }
public string var3{ get; set; }
public string var4{ get; set; }
public List<string> var5{ get; set; }
}
[HttpPost]
public IActionResult Report_2(FilterModel filter)
{
FilterLogic filterLogic = new FilterLogic(_context);
var result = filterLogic.GetResult(filter);
return View();
}
In JS I use jQuery function $.post
$.post("/Reports/Report_2", { var1: $('#var1').val(), var2: var2, var3: var3, var4: var4, var5: var5});

Passing Multiple JSON objects via AJAX to ASP.Net PageMethod

I am trying to pass two JSON Objects to my Page Method via AJAX
I created a class in Code Behind and created a JSON Object Array in javascript.
Following are my two classes and Page Method
public class userModel
{
public string userid { get; set; }
public string Name { get; set; }
}
public class companyModel
{
public string companyid { get; set; }
public string Name { get; set; }
}
[WebMethod]
public static string TestJsonMethod(userModel[] users)
{
return "";
}
And Following is my Javascript
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: []};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company = {companyid: "4", Name:"TEST COMPANY"};
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
Up till this point my code is working fine.
What I want to do is to pass the company object to the Page Method as well like this
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}
You could merge the models into one model.
public class TestJsonModel
{
public UserModel UserModel { get; set; }
public CompanyModel CompanyModel { get; set; }
}
Then action looks like;
[WebMethod]
public static string TestJsonMethod(TestJsonModel model)
Also, Ajax request post data looks like;
data: JSON.stringify({UserModel:obj,CompanyModel:company})
I was trying out different ways of doing it and this one worked.
function TestJSON() {
//var JSONObject = { a: [], b };
var obj = {users: [], company: {}};
var user;
for (var i = 0; i < 3; i++) {
user = {
userid: i.toString(),
Name: "User" + i.toString()
}
obj.users.push(user);
}
var company_ = {companyid: "4", Name:"TEST COMPANY"};
obj.company = company_;
$.ajax({
url: "bulkconsignments.aspx/TestJsonMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(obj),
async: false,
cache: false,
success: function (msg) {
alert(msg.d);
}
});
}
And the Code behind Page Method remains same.
[WebMethod]
public static string TestJsonMethod(userModel[] users, companyModel company)
{
return "";
}

Passing data from Ajax to controller in asp.net mvc

I have a viewModel
public class School
{
public int SchoolId { get; set; }
public int BuildingId { get; set; }
public int FloorId { get; set; }
public int PlannedBy { get; set; }
public IEnumerable<HeadCountPerRoom> HeadCountPerRoom{ get; set; }
}
And my controller looks like this:
public JsonResult SaveHeadCount(IEnumerable<School>schoolViewModel,int action)
{
// my code
}
I have written the javascript model and ajax:
function myfuncton() {
var HeadCountPerRoom=[];
var MasterEntry=[];
HeadCountPerRoom.push({
Month: month,
Year: year,
HeadCountId: seatCountID,
SeatCount: SeatCount,
});
masterEntry= JSON.stringify({
schoolViewModel:{
SchoolId: SchoolId,
BuildingId: BuildingId,
FloorId: FloorId,
PlannedBy: PlannedBy,
HeadCountPerRoom: HeadCountPerRoom
},
action:3
});
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "../myController/SaveHeadCount",
data: masterEntry,
success: function (data) {
//code.
}
})
In the controller I am getting null in the schoolViewModel parameter and for the action parameter I am getting the value. Why I am getting null?
You are expecting a list of school and you your JS you're passing only ONE object. You should pass your model on your JS as an array:
schoolViewModel: [
{
SchoolId: SchoolId,
BuildingId: BuildingId,
FloorId: FloorId,
PlannedBy: PlannedBy,
HeadCountPerRoom: HeadCountPerRoom
}
]

How to create a nested ajax requests?

I have a WEB API that is working fine. I want to call an action that is a part of my API via Ajax request. It seems that it is easy and I had it working for simple requests. However, I tried to put nested calls and for some reason the data that is passed to the second request gets lost. I was wondering if it is a scope problem or something I did wrong in my code.
Here is the javascript code:
$("#submit_request").click(function () {
var firstName = $("#first_name").val();
var lastName = $("#last_name").val();
var faciltiy = $("#facility").val();
// Collecting all the documents into an array of JSON
var documents = [];
var request = JSON.stringify({
"PatientFirstName": firstName,
"PatientLastName": lastName,
"Facility": faciltiy
});
//the first request is working fine and it has a success state
$.ajax({
url: "http://localhost:64611/api/requests/createRequest",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: request,
success: function (request_id, state) {
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
console.log(documents); // it is returning a correct object
console.log(typeof (documents)); // type object
$.ajax({
url: "http://localhost:64611/api/requests/addDocumentsOfARequest/",
type: "post",
datatype: 'json',
contenttype: 'application/json',
data: JSON.stringify(documents), ---> this object should be passed to the api action
success: function (response, state) {
},
error: function (err) {
if (err) {
}
}
});
},
error: function (err) {
if (err) {
}
}
});
});
The definition of my api action is like the following
public async Task<IHttpActionResult> addDocumentsOfARequest(RequestDocument[] documents)
The class RequestDocument is like the following:
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
My WebApiConfig is like the following:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "defaultApiRoutes",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"\d+" } // Only matches if "id" is one or more digits.
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
the parameter 'documents' is empty. Any idea?
Thanks!
Here's my exact working code :
Server
public class GamesController : ApiController
{
// GET api/<controller>
[HttpPost]
public async Task<IHttpActionResult> Post(RequestDocument[] document)
{
var req = await Request.Content.ReadAsStringAsync();
return Ok();
}
}
public class RequestDocument
{
[Required]
public int RequestID { get; set; }
[Required]
public int DocumentID { get; set; }
[Required]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
JavaScript
var documents = [];
for (var i = 0; i < 5; i++) {
var RequestDocument = {
"RequestID": i,
"DocumentID": i+1,
"StartDate": Date(),
"EndDate": Date()
};
documents.push(RequestDocument);
}
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(documents),
success: function(a, b) {
alert("Done");
}
});
Result
try this,
$.ajax({
url: "http://localhost:1757/api/games",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: {
document: documents
},
success: function(a, b) {
alert("Done");
}
});

How to pass multiple values as single object in Javascript/Ajax

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;
}

Categories