Background:
I have a jquery click function which should delete a picture from a model. For that I am sending an ajax request to my controller. To get the URL of this action I wrote an ActionResolver which works similar to the HTML helper of MVC. As you see in the code I used typescript and typescript collections.
My problem now is that as soon as the browser reaches "var routeValues = new collections. Dictionary();" it errors with "Uncaught ReferenceError: collections is not defined". I wrote at the top of the ts file "/// < reference path="typings/collections/collections.ts" />" so I can't figure out why it's not defined.
If anyone has a hint I would really appreciate it as I am just getting started with jscript and typedscript. :)
$(function () {
$(".jsPictureDelete").click(function () {
var controller = $("#Controller").attr('value');
var id = $("#Id").attr('value');
var propertyName = this.id.replace("pictureDeleteBtn", "");
var routeValues = new collections.Dictionary<string, string>();
routeValues.setValue("id", id);
routeValues.setValue("propertyName", propertyName);
var action : Action = new Action("DeletePicture", controller, routeValues);
//var url = '/' + controller + '/DeletePicture/' + id + '?propertyName=' + propertyName;
var url = action.ResolveAction();
$.ajax({
type: "GET",
url: url,
contentType: 'application/json; charset=utf-8',
success: function (returndata : any) {
alert("worked");
}
});
});
});
class Action {
private _controller: string;
private _action: string;
private _routevalues = new collections.Dictionary<string, string>();
constructor(action: string, controller: string, routevalues = new collections.Dictionary<string, string>()) {
this._controller = controller;
this._action = action;
this._routevalues = routevalues;
}
public ResolveAction() : string {
var result: string = "/" + this._controller + "/" + this._action;
var attrib: boolean = false;
if (this._routevalues.containsKey("id")) {
result += "/" + this._routevalues.getValue("id") + "?";
}
Object.keys(this._routevalues).forEach(function (key) {
if (key !== "id") {
result += key + "=" + this._routevalues[key] + "&";
attrib = true;
}
});
if (attrib) {
result = result.substring(0, result.length - 1);
}
return result;
}
}
referencing the collections.ts file only provides intellisense support in the editor.
you have to include that file (js equivalent?) in your webpage too.
You need to compile it with the --out flag.
Reference: https://youtube.com/watch?hd=1&v=KDrWLMUY0R0
Related
I am not able to get the data on the page using AJAX with Spring Boot. When I try the URL on postman it gets all the values from the database, but when I type the same URL in the browser it's only showing []. I have attached my code here please help me find a solution for this problem. The list of data is taken correctly.
Controller
#RequestMapping(value = "/getEasyQuestionsBySkill/{primarySkill}", method = RequestMethod.GET, produces = { MimeTypeUtils.APPLICATION_JSON_VALUE })
public ResponseEntity<List<EasyQuestions>> getAllEasyQuestions(#PathVariable String primarySkill) {
try {
ResponseEntity<List<EasyQuestions>> responseEntity = new ResponseEntity<List<EasyQuestions>>(easyQuestionsService.getEasyQuestionsBySkill(primarySkill), HttpStatus.OK);
return responseEntity;
} catch (Exception e) {
return new ResponseEntity<List<EasyQuestions>> (HttpStatus.BAD_REQUEST);
}
}
Thymeleaf - Javascript
$("#skillSubmitBtnId").on("click",function() {
var skill_name = $(".skillCls").val();
if(skill_name == ""){
alert("Select a Primary Skill");
}else {
$.ajax({
type: 'GET',
url: '/getEasyQuestionsBySkill/{'+skill_name+'}',
dataType: 'json',
success: function(result) {
var str = '';
for(var i=0; i<result.length; i++) {
str += '<br/> Question :' +result[i].question;
str += '<br/> Primary Skill :' +result[i].primarySkill;
str += '<br/> Secondary Skill :' +result[i].secondarySkill;
str += '<br/>';
}
$("#contentDivId").html(str);
}
});
$("#errorDivId").hide();
$("#javaTableDivId").show();
}
});
I am trying to apply a filter to data that is being displayed on a map but for some reason, the Ajax call that I have set up is not being executed. I can reach the console.log line in the view but anything after that in the Ajax call is never executed. This is being done in ASP.NET MVC.
I have similar Ajax calls in this project from other developers that function in a similar manner. I have tried to restructure my code to work in a similar manner, but with no success. The other developers have no idea what is going on either.
C# in the controller
[HttpPost]
public ActionResult MapFilter(string filterLake, bool filterPets)
{
var filteredProperties = db.Properties.Include(a => a.PropertyCategory).Where(b => b.Status == true).Select(x => new { x.PropertyName, x.PropertyId, x.RatePerNight, x.RatePerWeek, x.MarketingTitle, x.Latitude, x.Longitude, x.Pets, x.PropertyCategory.PropertyCategoryName });
if (filterLake != "")
filteredProperties = filteredProperties.Where(a => a.PropertyCategoryName == filterLake);
if (filterPets != true)
filteredProperties = filteredProperties.Where(a => a.Pets == filterPets);
var jsonProperties = JsonConvert.SerializeObject(filteredProperties);
return new JsonResult()
{
Data = jsonProperties,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
JavaScript & Ajax in the View
var filterLake, filterPets;
var btnApplyFilters = document.getElementById("applyFilters");
var filterLakeNode = document.getElementById("filterLake");
var filterPetsNode = document.getElementById("filterPets");
$(document).ready(function () {
btnApplyFilters.onclick = function () {
filterLake = filterLakeNode.options[filterLakeNode.selectedIndex].value;
filterPets = filterPetsNode.options[filterPetsNode.selectedIndex].value;
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
$.ajax({
url: "/Estates/MapFilter",
type: "Post",
data: {
"filterLake": filterLake,
"filterPets": filterPets
},
success: function (result) {
filteredMapData = result;
console.log("Result = " + result);
loadMapMarkers(true)
}
});
};
})
When I run the program on localhost, I am able to reach the
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
line with no issues. Anything after does not run.
You need check filterPets value, it must be true/false then model binder can map with bool type.
With primitive type (bool, int, float) you should use nullable type bool? for preventing case the value incorrect format.
[HttpPost]
public ActionResult MapFilter(string filterLake, bool? filterPets)
{
}
With this paramter if filterPets has wrong value, it will be null.
As the title say, I need to send from a .js file some values to a MVC controller, one of that values is an object array that corresponds to an List<> in the controller, the problem is that when arrives to the controller the List count is 0, this is my code:
In the .js:
var listaParametros = [
{ "Identificador": "1", "Tipo": "MG", "Texto": "Escala de calificación", "Valor": "/EscalaCalificacion/Listado", "IdRetorno": identificadorRetorno, "RecuerdaFiltros": recuerdaFiltros }
];
var maestroEscalaCalificacionE =
{
IdentificadorMaestroEscalaCalificacion: $('#grid-tableEscalaCalificacion').jqGrid('getRowData', elementoSeleccionado).IdentificadorMaestroEscalaCalificacion,
IndicadorActivo: $('#ddlIndicadorActivo').val(),
ListaParametros: listaParametros
};
$.redirectPost(window.rootUrl + "/EscalaCalificacion/Consultar", maestroEscalaCalificacionE);
The ActionResult on the Controller:
[HttpPost]
public ActionResult Consultar(EscalaCalificacionMaestroE maestroEscalaCalificacionE)
The List is a public property of the class EscalaCalificacionMaestroE.
By the way, I'm using $.redirectPost() because I need to go to another page when the ActionResult finishes.
[UPDATE]
This is the function redirectPost()
redirectPost: function (location, args) {
var form = '';
var jForm = $('<form></form>', {
action: location,
method: 'post'
});
$.each(args, function (key, value) {
$("<input>", {
name: key,
value: value,
type: 'hidden'
}).appendTo(jForm);
});
jForm.appendTo('body').submit();
}
Now, when I use $.ajax, all works like a charm, but don't know how to get the new page, any help on getting to the new page?
Thanks to everyone, your ideas help me to solve it, the architecture of the project, there are certain things that I can not use, but mixing ideas I solved it in the following way (I am aware that it is not the best in terms of security practices, but I can not change it):
I made a function similar to redirectPost () called "Redirection", but it would allow me to create an HTML input for each value in the list with the following format:
key: List [0] [PropertyName]
value: parameterValue
Then when the submit executes, the "List" on the controller has the right values.
Once again thanks everyone!
BTW, this is the code, maybe someone can need it!
function Redirection(location, args) {
var form = '';
var jForm = $('<form></form>', {
action: location,
method: 'post'
});
iterateValues(args, [], jForm, null, false)
jForm.appendTo('body').submit();
}
function getInput(name, value, parent, isArray, isTraditionalArray) {
var parentString;
if (parent.length > 0) {
parentString = parent[0];
var i;
for (i = 1; i < parent.length; i += 1) {
parentString += "[" + parent[i] + "]";
}
if (isArray) {
if (isTraditionalArray)
name = parentString;
else
name = parentString + "[" + name + "]";
} else {
name = parentString + "[" + name + "]";
}
}
return $("<input>").attr("type", "hidden")
.attr("name", name)
.attr("value", value);
};
function iterateValues(values, parent, form, isArray, isTraditionalArray) {
var i, iterateParent = [];
Object.keys(values).forEach(function (i) {
if (typeof values[i] === "object") {
iterateParent = parent.slice();
iterateParent.push(i);
iterateValues(values[i], iterateParent, form, Array.isArray(values[i]), isTraditionalArray);
} else {
form.append(getInput(i, values[i], parent, isArray, isTraditionalArray));
}
});
};
I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
})
I am trying to fill a dropdown using ajax and a controller action, but nothing seems to be happening when I click the button that triggers the action:
Ajax:
$.ajax({
url: '#Url.Action("GetBranch", "Report")',
type: "GET",
success: function (result) {
$("#dropdown2").append('<option value=' + result.BranchId + '>' + result.BranchName + '</option>');
}
});
Controller Action:
public ActionResult GetBranch()
{
var branch = new Branch();
var branchId = branch.BranchId;
var branchName = branch.BranchName;
return Json(new[]
{
new {Id = branchId, Value = branchName}
}, JsonRequestBehavior.AllowGet);
}
This is a practice I am not too familiar with so there could be something obvious missing. None of the answers here have been able to help me because I am trying to bind to an existing <select>; not a #DropdownListFor
It seems that the controller action is not getting hit with the ajax call, so nothing is getting returned.
Thanks for your help!
public JsonResult GetBranch()
{
var branch = new Branch();
var branchs = new List<Branch>();
var branchId = "Branch01"; //If only your branch id datatype is string
branch.branchId = branchId;
var branchName = "Name of Branch";//Name you want to give for your branch
branch.branchName = branchName;
branchs.Add(branch);
return Json(branchs.Select(t => new {Text = t.branchName, Value = t.branchId}), JsonRequestBehavior.AllowGet);
}