How to format a JQuery GetJSON - asp.net-mvc-3

I'm calling the server with:
var url = '#Url.Action("GetWhoBowls", "Home")';
$.getJSON(url, { "theDate": "calEvent.start" }, function (data) {
alert(data.name);
});
I've tried all permutation of quoting the 'theDate' and even calEvent.start as above .... in all cases the server complains that (from Firebug):
The parameters dictionary contains a null entry for parameter 'theDate' of non-nullable type 'System.Double' for method 'System.Web.Mvc.ActionResult GetWhoBowls(Double)' in 'MatchClubMVC.Controllers.HomeController'.
Firebug shows the parameters of the call as
theDate calEvent.start
Here is my controller method signature
public ActionResult GetWhoBowls(double theDate)
Could someone be so kind as to set me on the correct path?!

If you expect a double on your controller don't send a string (remove the simple quotes around calEvent.start otherwise you are sending this string literal to the server which obviously cannot be converted to double):
$.getJSON(url, { theDate: calEvent.start }, function (data) {
alert(data.name);
});
Also make sure that calEvent.start is a valid double value.

try
public ActionResult GetWhoBowls(double? theDate)
also the error is arising because you are sending a null value in { "theDate": "calEvent.start" }
EDIT
not sure whether this will solve the problem or not but try this
var url = '#Url.Action("GetWhoBowls", "Home")';
$.getJSON(url, { theDate: "calEvent.start" }, function (data) {
alert(data.name);
});
and modify the action result like this
public ActionResult GetWhoBowls(double theDate)
{
return(data,JsonRequestBehavior.AllowGet);
}
this will give the same errorif you send null from client

Related

My PUT request isn't working, it returns error 500, I'm not sure why

I want to update some data of my database. For that I'm using an ajax request that will change the value of one variable. However this put request isn't working, going straight to the error and giving me an error 500 in the console. Can someone understand why this is happening?
Here is my ajax request:
function atualizaBD(idmarcador, novoEstado) {
$.ajax
({
url: `/api/IgnicoesAPI/${idmarcador}`,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
Id: +idmarcador,
Estado: novoEstado
}),
success: function (result) {
alert(result);
},
error: function () {
alert("ocorreu um erro!")
}
});
}
Here is the PUT in my controller:
[HttpPut("{id}")]
public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicao, string novoEstado)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ignicao.Id)
{
return BadRequest();
}
var dataDecisao = DateTime.Now;
var ig = _context.Ignicoes.FirstOrDefault (ignicaoId => ignicaoId.Id.Equals(id));
if (ig != null)
{
ig.Estado = novoEstado;
ig.Latitude = ignicao.Latitude;
ig.Longitude = ignicao.Longitude;
//esta data vai depender da avaliação de cada uma das ocorrencias
ig.DataInicioPropostaIgnicao = ignicao.DataInicioPropostaIgnicao;
//esta data é colocada quando é definido o estado da ignição (aceite, recusado, em avaliação, concluido)
ig.DataDecisaoIgnicao = dataDecisao;
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IgnicoesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
The variable that I want to change is Estado to novoEstado
First of all, you're building an Ignicoes object in your AJAX request like this:
{
Id: +idmarcador,
Estado: novoEstado
}
Then you're updating properties from it on the server like this:
ig.Latitude = ignicao.Latitude;
ig.Longitude = ignicao.Longitude;
ig.DataInicioPropostaIgnicao = ignicao.DataInicioPropostaIgnicao;
Since you're not setting properties Latitude, Longitude, or DataInicioPropostaIgnicao when you build the Ignicoes object in your AJAX request, they will always be null here.
Second, you are setting the Estado property in the AJAX request, so you would want to do this on the server:
ig.Estado = ignicao.Estado;
Then you can remove the string novoEstado parameter from your PutIgnicoes method completely.
If you want to keep the string novoEstado parameter, you need to change to something like [FromQuery] string novoEstado then change your AJAX request to use:
url: `/api/IgnicoesAPI/${idmarcador}?novoEstado=${novoEstado}`
I suspect the string novoEstado parameter is coming into the PutIgnicoes method as null (since it's not defined as a query or route parameter). If it is a non-nullable foreign key, the your call to SaveChangesAsync wil fail with a foreign key constraint error.

$.ajax to send data vis HttpPost in aspnet5 is not working

this is a followup question to the one here Using $.ajax to send data via HttpPost in aspnet5, is not working
I have made the changes requested in the comments and a few other changes such as using the Json package from Newtonsoft.
Basically I have a column, and when you click the header a couple of input tags appear dynamically, to change column name and submit it. I want to change it and show it right away using ajax. The code to do this is below, and sorry but the code is in coffee script. Also I am using ASPNET5 RC1 with MVC6.
SumbitColumnForm = () ->
$('.panel-heading').on 'click', 'input.ColumnTitleSumbit', (event) ->
event.preventDefault();
columnName = $('.NewColumnName').val().trim()
columnNumber = $(this).parent().parent().attr 'id'
$.ajax
url: '/Board/ChangeColumnName',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ColumnName: columnName, ColumnNumber: columnNumber})
success: (data) ->
alert "Hit the Success part"
alert 'data is' + data
panelHeading = $('input.ColumnTitleSubmit').parent()
$(panelHeading).html("<h3 class='panel-title'> <h3>").text(data)
error: (xhr, err) ->
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
The relevant action methods from the controller are below
[Route("{p_BoardName}")]
public IActionResult Show(string p_BoardName)
{
m_Board.BoardName = p_BoardName;
ViewData["BoardName"] = m_Board.BoardName;
return View(m_Board);
}
[HttpPost]
public JsonResult ChangeColumnName(string newColumnData)
{
ColumnModel column = JsonConvert.DeserializeObject<ColumnModel>(newColumnData);
// Update column name in the board model, the board model stores a list of columns
m_Board.ColumnList[column.ColumnNumber].ColumnName = column.ColumnName;
var json = JsonConvert.SerializeObject( m_Board.ColumnList[column.ColumnNumber]);
return Json(json);
}
Also the column and board models are below
public class ColumnModel
{
private string m_name;
private int m_columnNumber;
public int ColumnNumber { get { return m_columnNumber; } set {m_columnNumber = value;} }
public string ColumnName { get { return m_name;} set { m_name = value; } }
public ColumnModel(string p_Name, int p_ColumnNumber)
{
m_name = p_Name;
m_columnNumber = p_ColumnNumber;
}
public ColumnModel() { }
}
public class BoardModel
{
private string m_BoardName;
private List<ColumnModel> m_ColumnList;
[Required]
public string BoardName { get { return m_BoardName; } set { m_BoardName = value; } }
public List<ColumnModel> ColumnList
{
get { return m_ColumnList; }
set { m_ColumnList = value; }
}
}
I have done a lot of googling and I still can't get this to work. The request is not hitting the success attribute and is hitting the error attribute. I still get a 200 status code to show it is OK, and for some reason my data is a long html file, or in this case the 'Show' view from the board controller. I have requested requested Json and I am getting html. I don't know what is going on, I feel what might be going wrong is the http post method ChangeColumnName in the controller. Maybe I am not receiving or sending a valid JSON object. Any help will be greatly appreicated.
The key here is [ValidateInput(false)]
Try this :
Rather than sending a JSON.stringify, just send it as an object which means
var Data = {ColumnName: columnName, ColumnNumber: columnNumber};
You were already doing this from your link!
Change your signature to receive your ColumnModel directly rather than a string and add the attribute [ValidateInput(false)] to your action. You'll not need to deserialize with this approach!
[ValidateInput(false)]
public JsonResult ChangeColumnName(ColumnModel newColumnData)
{
Console.WriteLine(newColumnData.ColumnName);
}
Let me know if this solves your problem!
You are supplying the correct variable
in ajax
data: {ColumnName: columnName, ColumnNumber: columnNumber}
In controller
[HttpPost]
public JsonResult ChangeColumnName(string ColumnName, int ColumnNumber)
{
..your code..
}
hope this helps

Knockout computed observable boolean that uses an ajax call not returning boolean on sucess

I have a knockout pureComputed observable that is supposed to return if a account number is valid.
First it checks if the field is empty. (returns false)
Then it checks to see if the account number has changed from what was loaded. (returns true)
Finally it will run the ajax call to get the account info.
If successful it will set the ErrorMessage from the object and the Customer info. Then it is supposed to return true or false based on the ErrorMessage.
If unsuccessful it will set the ErrorMessage and return false.
self.isAccountValid = ko.computed(function () {
if (!self.account()) {//If not complete mark as InValid
self.accountError("Account Number Incomplete.")
return false;
} else if (vm.account == self.account()) {
self.accountError("");
return true;
} else {
var deferred = $.Deferred();
return $.ajax({
url: '/Order/NumberValidation',
data: { account: self.account() }
}).success(function (data) {
self.accountError(data.ErrorMessage);
//Set customer info properties
self.setCustomerInfo(data);
//Set success or warn icon based on error message field
var isValid = !data.ErrorMessage;
deferred.resolve(isValid);
return deferred;
}).error(function (data) {
//Set error message for invalid account
self.accountError("Server error. Please try again in a few minutes.");
//Set warning icon
return false;
})
}
}).extend({ async: ko.observable() });
They extend is a method I found to allow the computed to wait on the ajax call:
ko.extenders.async = function (nonObservableComputed, observableResult) {
nonObservableComputed.subscribe(function (result) {
jQuery.when(result).then(observableResult);
});
return observableResult;
}
This is setting the other data correctly on success, but the return of !data.ErrorMessage which evaluates to false if looking at it through debug is not what is set for the value of isAccountValid. Instead it is being set to the whole data object even though I am trying to return just the boolean.
myViewModel.isAccountValid()
Object {FirstName: null, LastName: null, StreetAddress: null, City: null, State: null…}
City: null
ErrorMessage: "Sequence contains no matching element"
FirstName: null
LastName: null
PhoneNumber: 0
State: null
StreetAddress: null
ZipCode: 0
One problem is that you're using a pureComputed for a function with side effects.
You also have an extra c in acccountError in your success section.
The extender is pretty horrible. It becomes trivial if you pass it the computed you want to use instead of its type, and don't need the added inProgress member.
ko.extenders.async = function (nonObservableComputed, observableResult) {
nonObservableComputed.subscribe(function (result) {
jQuery.when(result).then(observableResult);
});
return observableResult;
}
Demo: http://jsfiddle.net/sp160tan/1/
Update
Pretty sure your problem is that you're returning the ajax result rather than the deferred. Also, the success and error callbacks don't need to return anything; their return values are not used. This could be a source of confusion.
} else {
var deferred = $.Deferred();
$.ajax({
url: '/Order/NumberValidation',
data: { account: self.account() }
}).success(function (data) {
self.accountError(data.ErrorMessage);
//Set customer info properties
self.setCustomerInfo(data);
//Set success or warn icon based on error message field
var isValid = !data.ErrorMessage;
deferred.resolve(isValid);
}).error(function (data) {
//Set error message for invalid account
self.accountError("Server error. Please try again in a few minutes.");
//Set warning icon
deferred.resolve(false);
})
return deferred;
}

Kendo grid how to pass additional parameter from java script

in telerik extenstion to pass additional data to ajax request I used
function onDataBinding(e)
{
e.data = {argument : 4};
}
where e was div cointainer with data object inside,
How can I do this using kendo ? I tried the same but for Kendo e arqument is sth totally different.
Finally i got the answer my own and it is :
$('#grid').data('kendoGrid').dataSource.read({name:value})
Sorry for the terrible late at the party, but i've got some special cake that you may find tasty:
function readData()
{
return {
anagId: selectedItem.ID
};
}
$("#grid").kendoGrid({
dataSource: {
type: "ajax",
transport: {
read: {"url":"#Url.Action("RecordRead", "Tools")","data":readData}
}
[ rest of the grid configuration]
I came across this code by inspecting the code generated by Kendo Asp.Net MVC helpers.
I don't know if this is a further implementation that didn't exist at the age of the post, but this way looks really the most flexible compared to the other answers that i saw. HTH
Try this:
Add this to your grid read function or any CRUD operation:
.Read(read => read.Action("ReadCompanyService", "Admin").Data("CompanyServiceFilter"))
Add javascript:
function CompanyServiceFilter()
{
return {
company: $("#ServiceCompany").val()
}
}
In your controller:
public ActionResult ReadCompanyService([DataSourceRequest]DataSourceRequest request, string company)
{
var gridList = repository.GetCompanyServiceRateList(company);
return Json(gridList.ToDataSourceResult(request));
}
Please note, only string type data is allowed to be passed on read, create, update and delete operations.
If you want to pass some param to ajax request, you can use parameterMap configuration on your grid.
This will get passed on to your Ajax request.
parameterMap: function (options, operation) {
if (operation === "read") {
var selectedID = $("#SomeElement").val();
return {ID: selectedID }
}
return kendo.stringify(options.models) ;
}
Try this:
.Read(read => read.Action("Controller", "Action")
.Data(#<text>
function() {
return {
searchModel: DataFunctionName(),
userName: '#=UserName#'
}
}
</text>)
)
JS function
function DataFunctionName() {
var searchModel = {
Active: $("#activityMonitorIsActive").data('kendoDropDownList').value(),
Login: $("#activityMonitorUsers").data('kendoComboBox').value()
};
return searchModel;
}

How to make Dajax callback into scoped object

I cant seem to find a way to make django-dajaxice have its callback inside same scoped object from which made the initial call.
MyViewport = Ext.extend(MyViewportUi, {
initComponent: function() {
MyViewport.superclass.initComponent.call(this);
},
LoadRecordsCallback: function(data){
if(data!='DAJAXICE_EXCEPTION')
{ alert(data); }
else
{ alert('DAJAXICE_EXCEPTION'); }
},
LoadRecords: function(){
Dajaxice.Console.GetUserRecords(this.LoadRecordsCallback);
}
});
var blah = new MyViewport();
blah.LoadRecords();
I'm on django, and like the calling syntax to django-dajaxice. I'm using Extjs 3.2 and tried passing a Ext.createCallback but Dajax's returning eval seems to only want a string for the callback.
BozoJoe, this should work.
MyViewport = Ext.extend(MyViewportUi, {
initComponent: function() {
MyViewport.superclass.initComponent.call(this);
},
LoadRecordsCallback: function(data){
if(data!='DAJAXICE_EXCEPTION')
{ alert(data); }
else
{ alert('DAJAXICE_EXCEPTION'); }
},
LoadRecords: function(){
Dajaxice.Console.GetUserRecords('blah.LoadRecordsCallback');
}
});
var blah = new MyViewport();
blah.LoadRecords();
I'm not familiar with django at all, but I think I understand the problem.
It seems that the API mandates that you pass a string which will be eval'd as a function call, so you must pass the name of the function, rather than the function itself.
This in turn means that it must be a name that is meaningful at the window scope - either a function defined outside of an Ext class (e.g. "myGlobalFunction"), or a member function of an Ext class that is accessible as a variable (e.g. "window.blah.LoadRecordsCallback")

Resources