asp.net mvc not getting value from ajax when converting data into json.stringify - ajax

I am using a event handler that checks if the product id or name already exist. But my problem is when I am using JSON.stringify() my C# controller does not receive the data from the ajax call,.
// check if Product name already exist
$('#productName').bind('keyup blur', function () {
// check if input is empty
if ($(this).val().length > 0) {
var data = JSON.stringify({
value: $(this).val(),
fieldName: 'productName'
});
$.ajax({
type: "post",
url: '/Product/ValidateProductDetailsExist',
contenttype: "application/json; charset=utf-8",
datatype: "json",
data: data,
context: this,
success: function (result) {
if (result === true) {
// append error message
// check if error message already exist
if ($('#errorprodcutName').length === 0) {
var errormessage = '<div class="col-md-offset-2"><span id = "errorprodcutName" class="validation-error-message">Product name already exist</span></div >';
$('.form-group:nth-child(2)').append(errormessage);
}
$(this).focus();
//disables the save button
$('#btnSaveProduct').prop('disabled', true);
}
else {
// check if error message already exist
if ($('#errorprodcutName').length > 0) {
$('#errorprodcutName').remove();
}
//enables the save button
$('#btnSaveProduct').prop('disabled', false);
}
},
error: function () {
alert("unable to request from server");
}
});
}
});
When I use debugger to check the value, it is null. I don't see any errors that displays in the console as well. Can anyone please explain to me why it is not working.
public JsonResult ValidateProductDetailsExist(string value, string fieldName)
{
using (POSEntities3 db = new POSEntities3())
{
bool isExist = false;
switch (fieldName)
{
case "productId":
var dataItemProductId = db.Products.Where(product => product.product_id == value).SingleOrDefault();
isExist = (dataItemProductId != null);
break;
case "productName":
var dataItemProductName = db.Products.Where(product => product.name == value).SingleOrDefault();
isExist = (dataItemProductName != null);
break;
}
return Json(isExist, JsonRequestBehavior.AllowGet);
}
}

Related

Telerik Kendo MVC Grid Validation Always Fails

I am tearing my hair out with this...!
I have a telerik kendo mvc ui grid widget using an Inline gridedit mode. When the user adds a new entry to the grid (by way of a custom dropdown edit control), I want it to validate that this entry is not already present in the grid.
I have an MVC controller action that does this and returns True or False accordingly. This works perfectly. Here is the validator javascript code I am using.
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: {
bedQuantity: function (input, params) {
if (input.is("[name='Quantity']") && input.val() <= 0) {
input.attr("data-bedQuantity-msg", "Quantity must be 1 or more");
return false;
}
return true;
},
bedExists: function(input, params) {
if (input.is("[name='BedType']")) {
var model = {
PropertyId: #Model.Id,
BedTypeId: input.val()
};
var url = "/Property/ValidateBedTypeExists";
input.attr("data-val-bedExists-requested", true);
$.ajax({
type: "POST",
url: url,
traditional: true,
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
success: function(data) {
return data === false;
},
fail: function(data) {
return false;
}
});
} else {
return true;
}
}
},
messages: {
bedQuantity: function (input) {
return input.attr("data-val-bedQuantity");
},
bedExists: function(input) {
return "This bed type already exists";
}
}
});
})(jQuery, kendo);
No matter whether the ajax call returns true or false, the validator always flags the entry as invalid.
You can give the html attribute for the kendoDropdownList as required like this
#(Html.Kendo().DropDownList()
.DataValueField("")
.DataTextField("")
.Name("")
.HtmlAttributes(new { required ="required" })
.OptionLabel("- Select a type - ")
.Filter(FilterType.Contains)
)
Try this..

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

JQuery Datatable memory leak under both IE and Chrome

My application is using Datatable which binds the data and event dynamically. When monitored from Developer tool in internet explorer one can see an increase in the total memory usage after each server successful response (increases approx. 29-35 MB). I tried solutions to free the DOM using jquery remove(), empty(), detach(), and destroy() methods but none stops the memory increase. Even destroying the datatable before request doesn't help. I also tried to delete the variables in the script, set the variables to null, and set the event bind to the datatable off().
The code snippet from the js file is as follows
function LoadData(isReset) {
var viewId = $jq('#ddlCategory').val();
if (viewId == 'undefined' || viewId == null || viewId == '') {
return false;
}
try {
//Clear the variables and remove the datatable
ClearFunction();
dtAjaxCall = $jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/GetData",
deferRender: true,
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
timeout: 0,
headers: { Connection: 'keep-alive' },
data: JSON.stringify({
"viewId": viewId
}),
success: function (response) {
//Clear the variables and remove the datatable
ClearFunction();
result = response.d;
if (result.IsError) {
CustomConfirm("dialog-confirm", result.Message, "");
}
else if (result.Data != null) {
data01 = result.Data;
result.Data = null; //set the result.Data as null
tableHeaders = ''; //var to store Datatable headers
columns = []; //var to store Datatable columns
excludeFilters = [];//var to exclude the filters.
bulkOperation = data01.BulkOperation; //var to store if bulk operation is required
//Create the table header columns dynamically as configured in database
$jq.each(data01.Columns, function (i, val) {
if (val.HiddenColumn != "Y") {
tableHeaders += "<th>" + val.DisplayName + "</th>";
var col = { 'title': val.DisplayName, 'data': val.DataColumnName.toLowerCase() };
columns.push(col);
}
if (val.FilterColumn >= 0) {
excludeFilters.push(val.FilterColumn);
}
});
data = $jq.parseJSON(data01.Results); //result returned in ajax call
json = $jq.parseJSON(data01.WorkListJQStructure); //datatable configuration returned in ajax call
delete json["bAutoWidth"];
json.data = data;
json.columns = columns;
DisplayExportOptions(json.buttons, 'resultsTable', 'ulExportTo');
//Add checkbox for each row in the data table
dtColumnDefinition = function (data, type, full, meta) {
return '<input type="checkbox" data-id="' + data + '">';
}
json.aoColumnDefs[0].render = dtColumnDefinition;
//Ajax call to save the datatable state state
dtSaveState = function (settings, data) {
$jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/SaveState",
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
data: JSON.stringify({ "viewId": viewId, json: data }),
"success": function () {
},
error: function (request, status, error) {
CustomConfirm("dialog-confirm", "An error occurred while processing your current request. Please try again", "");
}
});
}
//Try destroying the existing instance
if ($jq.fn.DataTable.isDataTable('#resultsTable')) {
$jq('#resultsTable').DataTable().destroy();
}
//Make the body empty
$jq('#resultsTable tbody').empty();
//Remove the datatable
$jq("#resultsTable").dataTable().remove();
//Datatable save state function call
json.stateSaveCallback = dtSaveState;
//Empty from the parent table of the datatable
$jq("#resultsTable_display").empty();
//Create the datatable header dynamically and add to the parent table
$jq("#resultsTable_display").append('<table id="resultsTable" class="display" style="width:100%;white-space: nowrap;"><thead><tr>' + tableHeaders + '</tr></thead></table>');
//bind the json and data to the datatable
SearchTable = $jq("#resultsTable").DataTable(json).rows().invalidate().draw();
//Set the event off before
$jq("#resultsTable").off();
//Set the event
$jq('#resultsTable').on('length.dt', function (e, settings, len) {
//code to set the height dynamically...
});
$jq("#resultsTable_display .dataTables_scrollHeadInner").css("width", "100%");
$jq("#resultsTable_display .dataTables_scrollHeadInner .dataTable").css("width", "100%");
BulkOpr(bulkOperation, SearchTable);
//reset the columns after binding the data
SearchTable.columns.adjust();
DataTableName = '#resultsTable';
$jq('#resultsTable').on('page.dt', function () {
info = SearchTable.page.info();
customHeight = 0;
customHeight = UserDefinedFields.CustomPageHeight(info, 40);
$jq('#Parent').attr('style', 'min-height:' + customHeight + 'px;');
});
$jq("a").removeClass("dt-button");
}
//set the variables null
json = null;
data01 = null;
data = null;
},
error: function (request, status, error) {
//do nothing...
}
});
return false;
}
finally {
//Clear the variables...
}
}
//----------------------------------------------
//method to clear the variables and datatables
function ClearFunction()
{
//make all variables null
dtAjaxCall = null;
resultSearchTable = null;
DataTableName = null;
info = null;
customHeight = null;
cells = null;
selected = null;
cBox = null;
clist = null;
dtSaveState = null;
result = null;
data01 = null;
tableHeaders = null;
columns = null;
excludeFilters = null;
bulkOperation = null;
data = null;
json = null;
dtColumnDefinition = null;
//clear dom objects
$jq("#resultsTable").dataTable().remove();
$jq("#resultsTable_display").dataTable().empty();
}
Thanks!
We are refreshing a datatable in a polling method, and it seems to lock up the browser. I don't have an answer either.

ASP.net cascading dropdown list

trying to implement country state dropdown in mvc but couldn't..
conotroller :-
[HttpGet]
public ActionResult GetCities(int StateId)
{
Business.Services.City cityService = new Business.Services.City();
List<Business.Models.City> stateList = cityService.GetCityByStateId(StateId);
//var jsonSerialiser = new JavaScriptSerializer();
//var json = jsonSerialiser.Serialize(stateList);
return Json(new { stateList }, JsonRequestBehavior.AllowGet);
}
method:
public List<Models.City> GetCityByStateId(int StateId)
{
try
{
var list = new List<SelectListItem>();
Collection<DBParameters> parameters = new Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "StateId", DBType = DbType.Int32, Value = StateId });
var city = this.ExecuteProcedure<Models.City>("GetCityByState", parameters).ToList();
//if (city != null && city.Count > 0)
//{
// list = city.Select(x => new SelectListItem { Text = x.CityName, Value = x.StateId.ToString() }).ToList();
//}
return city;
}
catch (Exception ex)
{
throw;
}
}
change event:
$('.ddlstate').change(function () {
debugger;
$.ajax({
url: '#Url.Action("GetCities", "User")',
type: "GET",
data: { StateId: $(this).val() },
dataType: "json",
success: function (result) {
debugger;
//alert(result.stateList[0].CityId);
$.each(result.stateList, function () {
debugger;
$('.cityddl').append($("<option></option>").val(CityId).html(CityName));
});
},
error: function (result, status, jQxhr) {
alert("Error: " + result + "-" + status + "-" + jQxhr);
}
});
});
i get count of the citites in method and controller but when i run project and change state dropdown i got blank city dropdown. what is wrong?
It looks like you're missing a couple of things in the $.each() call.
You should pass the JSON result from the ajax call to the $.each
You also need to provide a parameter to the callback function so that the callback function has something to work with
It could look something like this:
$.each(result.stateList, function(index, city) {
$('.cityddl').append($("<option></option>").val(city.CityId).html(city.CityName));
});

Kendo pager will not reset back to the first page

I have a made a kendo datasource which makes a call out to my api, I have it limited to make pages of 10's. My problem is that the pager will not set back to the first page. For example, when I make a call and to my api and receive 50 results, I will have 5 pages of 10 items each. I select to go to the fifth page which, I then make another call and only receive 10 items which makes one page. However then the cal completes I am still on the 5th page; it will not reset to the first page.
var dataSource = new kendo.data.DataSource({
page:1, << From what I read this is suppose to do the job
pageSize: 10,
transport: {
read: {
type: "POST",
url: location + "/api/ContentSearch/SearchRequest",
contentType: 'application/json',
beforeSend: function (req) {
req.setRequestHeader("Authorization", "Bearer " + token);
}
},
parameterMap: function (option, operation) {
return JSON.stringify(query);
}
},
change: function (e) {
var data = this.data();
$("#searchButton").prop("disabled", false);
$("#loadingGif").hide();
//kendoPager.page(1); << does not work
switch (data.length) {
case 0:
FeedBackMessage("No result found");
break;
case 500:
FeedBackMessage("Please check or refine the search");
break;
default:
$('#pager').show();
$('#descriptionColumn').show();
$("#listView").show();
$("#keyWordText").val("").data("kendoDropDownList").text("");
$("#searchText").val("");
}
return data;
},
error: function (e) {
$("#loadingGif").hide();
ErrorHandler(e.sender.transport.options.read.url, e.xhr.status, e.xhr.statusText, "Kendo datasource was not binded to the WebApi response", "", true);
}
});
function SubmitSearch(e) {
e.preventDefault();
query = {
SearchText: $("#searchText").val(),
KeywordText: generalContentKeywords.text(),
GlobalSearch: true
};
if (query.SearchText === "" && query.KeywordText === "Select Category") {
FeedBackMessage("Please enter a value");
}
else {
if (query.KeywordText === "Select Category") {
query.KeywordText = "";
}
$.when(TokenForWebApi()).then(function (adalToken) {
token = adalToken;
$('#pager').hide();
$('#descriptionColumn').hide();
$("#listView").hide();
$("#searchButton").prop("disabled", true);
$("#loadingGif").show();
dataSource.read();
});
}
};
var kendoPager = $("#pager").kendoPager({
dataSource: dataSource,
}).data("kendoPager");
I went around this issue, by changing my submit function to see if the datasource has any data, and if it find that it does it reset set the page back to one. I am guessing that my previous code, I was trying to set a page value before the datasource had any values to page.
function SubmitSearch(e) {
e.preventDefault();
query = {
SearchText: $("#searchText").val(),
KeywordText: generalContentKeywords.text(),
GlobalSearch: true
};
if (query.SearchText === "" && query.KeywordText === "Select Category") {
FeedBackMessage("Please enter a value");
}
else {
if (query.KeywordText === "Select Category") {
query.KeywordText = "";
}
$.when(TokenForWebApi()).then(function (adalToken) {
if (dataSource._pristineData.length) {
kendoPager.page(1);
}
token = adalToken;
$('#pager').hide();
$('#descriptionColumn').hide();
$("#listView").hide();
$("#searchButton").prop("disabled", true);
$("#loadingGif").show();
dataSource.read();
});
}
};

Resources