How to get data from json in lightgallery jquery? - javascript

I face with a problem in use lightgallery with jquery .When I use constant value for src and thumb it works great, but in the opposite it doesn't work with json . I see this kind of error in firebug.
Error
-data-src is not provided on slide item
HTML Code
<a id="dynamic" href>Open lightGallery</a>
$('#dynamic').on('click', function(e) {
var arr='';
$.ajax({
type: 'post',
url: "#Url.Action("ShowMenuGallery", "Ads")",
contentType: 'application/json; charset=utf-8',
data: '{"ID":"' + #Model.ID + '"}',
traditional: true,
success: function (data) {
arr=data;
console.log(arr);
}
});
$('#dynamic').lightGallery({
dynamic: true,
html:true,
dynamicEl: JSON.stringify(arr)
})
});
Controller.cs
public ActionResult ShowMenuGallery(int id)
{
ViewBag.guid = Guid.NewGuid();
List<string> menuImage = new List<string>();
ReturnImages(((Guid)ViewBag.guid).ToString(), id, ref menuImage);
List<MyClass> data = new List<MyClass>() { new MyClass() { src =menuImage[0] , thumb = menuImage[0] } };
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
operations = data
});
return Json(json);
}
public class MyClass
{
public string src { get; set; }
public string thumb { get; set; }
}

Try once this code
jQuery(document).ready(function($) {
$("#dynamic").on("click", function(e) {
$.ajax({
type: "post",
url: "#Url.Action("ShowMenuGallery", "Ads")",
dataType: "json",
data: {ID: "#Model.ID"},
traditional: true,
success: function (data) {
$("#dynamic").lightGallery({
dynamic: true,
html:true,
dynamicEl: JSON.stringify(data)
});
}
});
});
});
For more information see https://boxoverflow.com/get-json-jquery-ajax/

Related

What's the correct way to create class in JavaScript and pass that to MVC controller

I have a complex form with different tabs, so my ask is to save the entire form data to database on final save. I have the models as per my database as follows, posting sample class
public class VesselDetail
{
public string VesselName { get; set; }
}
public class MainModel
{
public VesselDetail VesselDetail { get; set; }
}
I have created JavaScript models as follows
class VesselDetail {
constructor() {
}
VesselName;
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}
On my save I am framing the data as follows
let data = new MainModel();
let vesselDetail = new VesselDetail();
vesselDetail.VesselName = "XYZ";
data.VesselDetail.push(vesselDetail);
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: '{mainModel: ' + JSON.stringify(data) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
My controller is as follows
[HttpPost]
public JsonResult PostUserData(MainModel mainModel)
{
return new JsonResult { Data = "OK" };
}
Somehow I am unable to see the vessel name that was given. I would like to know are my JavaScript models are correct or should I do any changes? Any better idea to make these models in JavaScript.
Don't hand-construct JSON, it's really easy to get it wrong. In this case, you haven't put the necessary " around mainModel in the JSON you're sending the server, which makes it invalid. As a result, the server won't be able to parse the JSON it receives.
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: '{mainModel: ' + JSON.stringify(data) + '}',
// ^−−−−−−−−^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− missing quotes
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
Instead, let JSON.stringify do it for you:
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: JSON.stringify({mainModel: data}),
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
Also, unless your server is returning JSON you're not using, you don't need dataType. (Even if it is, it should be returning the correct Content-Type header in which case dataType is redundant anyway.)
I also suggest either consistently using property declaration syntax (which is fairly new) or consistently not using it:
Not using it:
class VesselDetail {
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}
Using it:
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = [];
}
Here's an example of the JSON that will be produced by your code with the changes above (I've used property declaration syntax — the second set of classes above — but they'll both produce the same thing):
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = [];
}
let data = new MainModel();
let vesselDetail = new VesselDetail();
vesselDetail.VesselName = "XYZ";
data.VesselDetail.push(vesselDetail);
const json = JSON.stringify({mainModel: data});
console.log(json);
As you can see, VesselName is not blank.
try this, it was tested in VS2019 and working properly
var mainModel= { VesselDetail : { VesselName :"XYZ"} };
$.ajax({
url: '/Controller/PostUserData',
type: 'POST',
data: { mainModel: mainModel),
success: function (result) {
hideSpinner();
alert(JSON.stringify(result));
},
error: function (request) {
hideSpinner();
}
});
and fix VesselDetail class by adding setter and getter
public class VesselDetail
{
public string VesselName { get; set;}
}
And I see a bug in your action. What is a Data?
return new JsonResult { Data = "OK" };
try this
return new JsonResult(mainModel.VesselDetail.VesselName);
but if you like it a hard way you can try this
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = {};
}
let mainModel= new MainModel();
data.VesselDetail.VesselName="XYZ";
UPDATE
Sometimes this working better, depending on net version or if you are using API controller
var mainModel= { VesselDetail : { VesselName :"XYZ"} };
$.ajax({
url: '/Controller/PostUserData',
type: 'POST',
data: JSON.stringify(mainModel),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
alert(JSON.stringify(result));
},
error: function (request) {
hideSpinner();
}
});
but you have to add [FromBody] to action
[HttpPost]
public JsonResult PostUserData([FromBody] MainModel mainModel)
{
return new JsonResult(mainModel.VesselDetail.VesselName);
}
you put the VesselName out of the builder
should be like this
class VesselDetail {
constructor() {
this.VesselName;
}
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}

Ajax POST an object with javascript, but the value in backend is null, why?

So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.

How to call Javascript function on Url.Action on Kendo toolbar?

I have a kendo grid with a toolbar . I added a link to download from the toolbar and now the problem is i can't call Javascript function which goes to the controller with data.
How can i call java script function on Url.Action ?
Toolbar
.ToolBar(toolBar => toolBar.Template("<a onclick='getData()' href ='" + Url.Action("", "", null, "https") + "?SeletectOrders=#= SeletectOrders#'" + ">Download Selected Orders</a>"))
If i put controller name and function, it pass an empty data to the controller and download empty file which shows at the bottom on browser. I am really not sure if am doing this correctly
Javascript function which goes to the controller
function getData(SeletectOrders)
{
$.ajax({
url: '#Url.Action("myAction", "mycontroller")',
type: "GET",
contentType: 'application/json; charset=utf-8',
dataType: "text",
data: { SeletectOrders: SeletectOrders },
traditional: true,
async: false,
cache: false,
complete: function (data) {
},
error: function () {
}
})
}
Controller
[HttpGet]
public virtual ActionResult myAction(string[] SeletectOrders)
{
List<string> ListPossDetails = new List<string>();
if (SeletectOrders != null)
{
string[] OrderArray = SeletectOrders;
foreach (var list in OrderArray)
{
ListPossDetails.Add(list);
}
}
//download methods here
Response.AppendHeader("Content-Disposition", "attachment; filename=" + possFilename);
ListPossDetails = null;
return File(fileBytes, type, possFilename);
}

Passing two parameters to another controller with js

This is a button passing parameter values to another controller. It works perfectly for passing one value to the CarController but when I pass two I see it passing in the vehicle page but the breakpoint on the CarController shows that the vin_num value passed but the stock_num is null
Passing one param, works perfectly.
Vehicle.js
$(".button").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Cars/setD",
data: JSON.stringify({ vin_num: this.id }),
success: function (result) {
window.location.href = '/Cars/Index';
}
});
});
CarController.cs
public JsonResult setD(string vin_num)
{
Session["vin_num"] = vin_num;
return Json(true, JsonRequestBehavior.AllowGet);
}
What I tried, for passing two values.
$(".button").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Cars/setD",
data: JSON.stringify({ vin_num: this.id, stock_num: this.id2 }),
success: function (result) {
window.location.href = '/Cars/Index';
}
});
});
CarController.cs
public JsonResult setD(string vin_num, string stock_num)
{
Session["vin_num"] = vin_num;
Session["stock_num"] = stock_num;
return Json(true, JsonRequestBehavior.AllowGet);
}
You can use the Route attribute:
[Route("api/car/{param}/{paramTwo}")]
public JsonResult GetSomething(int param, int paramTwo) {
}
You can find more information about Attribute Routing in the following link
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
Create a class for the object then pass that object:
public class Stock
{
string vin_num { get; set; };
string stock_num { get; set; };
}
in controller:
public JsonResult setD(Stock stock)
{
and use it:
data: JSON.stringify(stock:{ vin_num: this.id, stock_num: this.id2 }),
Alternatively:
var mydata= {stock { vin_num: this.id, stock_num: this.id2 }};
...
data: JSON.stringify(mydata),

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Categories

Resources