JSON data to Array - javascript

This is my Javascript function that gets data from the HTML form.
$(function postProduct() {
$('#btn').click(function() {
var productName = document.getElementById("name").value;
var productDetail = document.getElementById("detail").value;
var productCategory = document.getElementById("category").value;
var dimensions = [productName, productDetail, productCategory];
var keys = $.map(dimensions, function(value, key) {
return value;
});
$.ajax({
type: "POST",
url: "api/product/addproduct",
data: keys,
success: function(result) {
alert('successful : ' + result);
return result;
},
error: function(error) {
alert("Not Working..");
}
});
}
});
});
This is my controller:
[HttpPost]
[Route("api/product/addproduct")]
public IActionResult AddProduct([FromBody] string[] addproduct)
{
var pProductName= addproduct[0];
var pProductDetail= addproduct[1];
var pProductCategory= addproduct[2];
Hotel NewProduct = new Product();
{
NewProduct.ProductName= pProductName;
NewProduct.ProductDetail= pProductDetail;
NewProduct.ProductCategory= pProductCategory;
}
_db.Products.Add(NewProduct);
_db.SaveChanges();
//create a new route for post method by id
return CreatedAtRoute(new { id = addproduct}, addproduct);
}
So, I'm trying to pass the inputted form and pass it to the controller by AJAX, However, it just fails.
This is the function that I use to make the json data to an array:
var dimensions = [productName, productDetail, productCategory];
var keys = $.map(dimensions, function(value, key) {
return value;
});
Or should I recode my controller for accepting json data. If so, please give me an example on doing it. Sorry, I'm new at web api.
UPDATE:
This is my jsondata:
productName: name
productDeatil: detail
productCategory:category
This is my Array:
keys:(7) ["name", "detail", "category"]

In your Ajax request, assign the data key to the following value...
{ productName: document.getElementById("name").value, productDetail: document.getElementById("detail").value, productCategory: document.getElementById("category").value }
This is a typical JSON formatted object.
You could then also remove your variable assignments and map function.
Finally you'd need to look into how to process this formatted JSON in your controller.
I'm unsure of how to go about this in asp.net-core-mvc but it could be something as simple as changing
var pProductName= addproduct[0];
to
var pProductName= addproduct.productName

Is the spacing between NewProduct and properties such as .ProductName intentional?
NewProduct .ProductName = pProductName;
Shouldn't it be like this?
Hotel NewProduct = new Product();
NewProduct.ProductName = pProductName;
NewProduct.ProductDetail = pProductDetail;
NewProduct.ProductCategory = pProductCategory;
With simplified object creation:
Hotel NewProduct = new Product() {
ProductName= pProductName,
ProductDetail= pProductDetail,
ProductCategory= pProductCategory
};

add data: JSON.stringifly(keys) in ajax solve the problem. Thank you for everyone's help!

Related

Cannot get DOT NET CORE MVC to return multiple LINQ results to a view

I am able to pass one value from the controller method, see first cal query to return just the calorie value from the SQL LINQ query. However, I cannot get two colums, see my code controller code and javascript in the view below (I cannot work out what is causing zero data to be populated
I can see var mytext in javascript code return : {"foodCal":101,"foodVarient":"Vegan"}
public JsonResult GetCalories(string Productdata)
{
//THis is the orginal code which returns one value, CALORIES
//var calquery = (from c in _context.Foods
// where c.FoodName == Productdata
// select c.FoodCal).FirstOrDefault();
var calquery = (from c in _context.Foods
where c.FoodName == Productdata
select new
{ c.FoodCal, c.FoodVarient }
).FirstOrDefault();
if (calquery != null)
{
return Json(calquery);
}
else
{
calquery = null;
return Json(calquery);
}
}
<script src="/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
document.getElementById("FoodType").onchange = function ()
{
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetCalories")',
data: { Productdata: document.getElementById("FoodType").value },
success: function (data)
{
var mytext = JSON.stringify(data);
alert(mytext);
var obj = JSON.parse(json);
document.getElementById("FoodCalories").value = obj.foodCal;
document.getElementById("FoodHealth").value = obj.foodVarient;
}
});
}
});
</script>
I figured out the problem
var object =JSON.parse(mytext), not json
problem solved.
Hope other people benefit from this code.

Get all json key and value from an external json file in MVC with javascript

I am creating a web app in which I have a Json file in which I have many keys with values, like the following,
{
"Login_Header_Text": "Login",
"Login_Header_Recent_Updates": "Recent Updates",
"Login_TextBox_UserName": "User Name",
"Login_TextBox_Password": "Password",
"Login_Button_Login": "Log In",
"Login_ErrorMessage_Usernamerequired": "User name required",
"Login_ErrorMessage_Passwordrequired": "Password required.",
"Login_ErrorMessage_Invalid_Credentials": "Invalid user name/password",
}
and I can retrieve the values like the following
<script>
console.log('#HttpContext.GetGlobalResourceObject("", "Login_TextBox_UserName")');
</script>
now, how can I retrieve whole json file data and print that into my console,
Like, if I have 55 Records in the json file, whole data should be printed in console.log
what is the proper way to do this?
here is how i would do it. in C# and also in javascript
assum we have this js
var json = [{Name: "test", Passowrd:"test" }]
in C# i would convert this to class
public class myjson{
public string Name { get; set;}
public string Password { get; set;}
}
then with reflection call on the property
public GetValue(this myjson o, string propertyName){
return o.GetType().GetProperty(propertyName).GetValue(o);
}
in Jsvascript i would just call this
var value = json[0][property]
I hop this could help you
hello I think this can help you, I made a small example by picking up an answer written in Ajax and writing it in the console.
Look at the function in success, I think that's what you're looking for
function formToJSON(form) {
var obj = {};
var elements = form.querySelectorAll("input, select, textarea");
for (var i = 0; i < elements.length; ++i) {
var element = elements[i];
var name = element.name;
var value = element.value;
if (name) {
obj[name] = value;
}
}
return obj;
}
function test(id, url, method) {
var data = formToJSON(document.getElementById(id));
$.ajax({
type: method,
url: url,
data: data,
success: function (output, status, xhr) {
var response = JSON.parse(xhr.responseText);//<--- here is your JSON
for (var item in response) { // and set for to print indivual
console.log(item+' '+response[item]);
}
console.log(response);
},
cache: false
});
}

breeze doesn't recognize the modified entity

I have a breeze implementation where it takes a location object and displays the properties on the UI. I do a change to a few properties and try to save the changes, but breeze doesn't recognized the entity as changed. Following is my code:
[HttpGet]
[CustomAuthorize(Claims = "permission:CanViewLocationAttributes")]
public Location GetLocationById(int clientId, int locationId)
{
//returns a single Location object
}
Following is my client-side functionality to retrieve the entity and save the entity:
function getLocationById(clientId, locationId) {
var self = this;
return EntityQuery.from('GetLocationById')
.withParameters({ clientId: clientId, locationId : locationId })
.using(self.manager)
.execute()
.then(querySucceeded, this._queryFailed);
function querySucceeded(data) {
if (data.results.length > 0) {
return data.results[0];
}
logSuccess(localize.getLocalizedString('_RetrievedLocations_'), locations, true);
}
}
function saveLocationSettings(clientId) {
var self = this;
var saveOptions = this.manager.saveOptions.using({ resourceName: "SaveLocationSettings", allowConcurrentSaves: true });
var entitiesToSave = self.manager.getChanges();
return self.manager.saveChanges(entitiesToSave, saveOptions).then(saveSucceeded, saveFailed);
}
my problem is that here the value of entitiesToSave is 0, even after I make changes to the fields in UI and save them.
Following is how I bind the entity to my angular model:
function getLocationDetails() {
clientcontext.location.getLocationById($route.current.params.clientId, $route.current.params.id)
.then(function (data) {
basicLocationSettings.id = data.locationId;
basicLocationSettings.parent = data.fkParentLocationId;
basicLocationSettings.locationType = data.locationType;
basicLocationSettings.locationName = data.locationName;
basicLocationSettings.locationDisplayName = data.locationDisplayName;
basicLocationSettings.locationCode = data.locationCode;
basicLocationSettings.isActive = data.activeStatus;
basicLocationSettings.timeZone = data.fkTimeZoneId;
basicLocationSettings.usesAppointments = data.usesAppointments;
basicLocationSettings.availabilityWindowDays = data.availabilityWindowDays;
basicLocationSettings.appointmentCutOffDays = data.appointmentCutOffDays;
basicLocationSettings.dailySummaryEmailTime = data.dailySummaryEmailTime;
basicLocationSettings.reminderBeforeApptEmailTime = data.reminderBeforeApptEmailTime;
basicLocationSettings.saveLocationSettings = function () {
clientcontext.location.saveLocationSettings($route.current.params.clientId);
}
});
}
Can anyone explain what I'm doing wrong? This is my first attempt on breeze and I'm kind of stuck here.
It looks like you are copying the breeze location entity's property values into an pojo object variable named "basicLocationSettings". Any changes to basicLocationSettings will not be tracked by the breeze entity manager or reflected in the source breeze entity. You'll need to bind the actual breeze entity to your UI so that user data entry modifies the entity property values directly.
I modified my code as follows and now the save is working:
function getLocationById(clientId, locationId) {
var self = this;
var location = null;
return EntityQuery.from('GetLocationById')
.withParameters({ clientId: clientId, locationId : locationId })
.using(self.manager)
.execute()
.then(querySucceeded, this._queryFailed);
function querySucceeded(data) {
if (data.results.length > 0) {
location = data.results[0];
}
logSuccess(localize.getLocalizedString('_RetrievedLocations_'), locations, true);
return location;
}
}
Note that I'm returning a location object, and in my controller, I bind the location object to my POJO.
function getLocationDetails() {
clientcontext.location.getLocationById($route.current.params.clientId, $route.current.params.id)
.then(function (data) {
basicLocationSettings.location = data;
basicLocationSettings.saveLocationSettings = saveLocationSettings;
});
}
Now when I call saveChanges(), I pass the location object to the repository:
function saveLocationSettings() {
clientcontext.location.saveLocationSettings(basicLocationSettings.location);
}

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

Posting multiple objects in an ajax call

I have a list of data which is within multiple objects.
Each object has an ID and a status and then the main object has a type and a form id.
The problem I am having is posting result via ajax as it doesn't like the multiple objects.
This is the code I have:
var permissionsData = [];
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData.push(obj);
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: permissionsData
});
How can I wrap/send permission data?
How about changing your array to an object and using jQuery's param function.
var permissionsData = {};
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData[index] = obj;
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: $.param(permissionsData)
});
maybe you can use json2.js
it can parse the object to json string and parse the json string to object
you can use JSON.stringify method for parse object to json string

Categories

Resources