Passing an array of Javascript classes to a MVC controller? - javascript

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

Related

Return parameter null in controller from ajax

I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}

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 = [];
}
}

Passing Javascript variable to Java Controller (Spring-boot)

I'm new to this, so after I have read some solution about this but still not get it.
I have a var id = [] and want to pass it to my controller to delete it from database (SQL server)
My JavaScript
$('#deleteButton').click( function () {
var id = [];
var length = table.rows('.selected').data().length;
for(var i = 0; i < length; i++){
id.push(table.rows('.selected').data()[i][0])
}
$.ajax({
url: "",
//idk to put what into this url
//I think to put an url to show my var but i getting 404 and
//maybe im missing something in controller
//my url to access the project is: localhost:8084
method: 'POST',
data: {
idList: id
},
success: function (data) {
console.log(id);
}
});
console.log(id);
table.rows('.selected').remove().draw( false );
} );
My java controller
#Controller
#ComponentScans(value = { #ComponentScan })
public class CandidateController {
#Autowired
CandidateServiceImp candidateService;
//localhost:8084/manageCandidates is where i show datatable
//and var id = [] is getting from this table
#RequestMapping(value = { "/manageCandidates"})
public String manageCandidatesPage(Model model) {
model.addAttribute("listCandidates",candidateService.getAllCandidates());
return "manageCandidates";
}
}
Please instruct me to get var = id[] in controller
Thanks alot
There are three processes.
Add content-type: application/json in client-side ajax.
And enclose the data in JSON.stringify.
If the server-side Model is properly structured, add #RequestBody before the Model.
Use JSON:
Controller :
#RequestMapping(value = "/manageCandidates", method = RequestMethod.DELETE)
public #ResponseBody String manageCandidatesPage(HttpServletRequest request,#RequestBody String idjson) throws Exception
System.out.println("id"+idjson);
}
Ajax:- data: JSON.stringify(id),
$.ajax({
url: "",
type: "",
async: false,
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(id),
success: function(data) {
response = data;
}
});

how to submit a form with a local list from javascript

I have a list that i created it in javascript and I want to send it to controller :
function submit1() {
var list_id = [];
var i;
for(i = 0; i < #Model.Count(); i++){
var x =docuzment.getElementsByClassName("bt1")[i].getAttribute("id");
var xxx = document.getElementById(x).style.backgroundColor;
if (xxx == "tomato") {
list_id.push(x);
}
}
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {list_id: String},
success: function (data) { alert("SUCCESS"); }
});
}
controller :
public ActionResult add_invitations(List<string> ls )
{
ViewBag.a = ls.Count();
return View();
}
I always get null reference exception for ls>
You are not passing the correct parameter to the action, it expecting to get a parameter named ls, but in your data object you are passing a parameter named list_id.
Try changing it to this:
$.ajax({
type: "POST",
url: '#Url.Action("add_invitations", "invitations")',
data: {ls: list_id},
success: function (data) { alert("SUCCESS"); }
});

JQuery Success Function not firing

I have the following script. It runs, it passes the variables to the controller, the controller executes correctly, but for whatever reason the success function does not fire and therefore does not refresh my html. Instead the error fires off. Nothing is jumping out at me as to the cause. Thanks for the help!
$(function() {
$("#btnUpdateTick").unbind('click').click(function () {
var currenttick =
{
"TicketID":#Html.Raw(Json.Encode(Model.TicketID)),
"Title": $("#Title").val(),
"Creator": $("#Creator").val(),
"StatusID": $("#StatusID").val(),
"Description": $("#Description").val(),
"newComment":$("#txtAddComment").val(),
Cat:
{
"CatID":$("#ddCurrTickCat").val()
}
}
//var newcomment = $("#txtAddComment").val();
var conv = JSON.stringify(currenttick);
$.ajaxSetup({cache:false});
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
});
});
My controller:
[HttpPost]
public PartialViewResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return PartialView("TicketDetails", model);
}
Your controller is returning a view instead of json. You should be returning a JsonResult instead. Try this:
[HttpPost]
public JsonResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return Json(model);
}
If you want to return Partial view from ajax call then modify ur ajax request as :
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "html",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
Now "data" in ur success function will have html returned from PartialViewResult().

Categories

Resources