Telerik Kendo MVC Grid Validation Always Fails - validation

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..

Related

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

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

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

knockout validation for array of objects

I have an array of dynamically added objects and I want to validate this array for required fields and numeric values.
I have 3 buttons, one for adding note, another for removing note and one for saving
How to validate every object ?
.. the code:
$(function () {
var initialData = [{
Title: "",
NoteText: "",
Suggestion: "",
MediaTime: ""
}];
var CreateNewNoteModel = function (Notes) {
var self = this;
self.Notes = ko.observableArray(ko.utils.arrayMap(Notes, function (Note) {
return { Title: Note.Title, NoteText: Note.NoteText, Suggestion: Note.Suggestion, MediaTime: Note.MediaTime };};
}));
var i = 1;
self.addNote = function () {
self.Notes.push({
Title: "", NoteText: "", Suggestion: "", MediaTime: ""
});
$('#editor' + i).wysihtml5();
$('#editorB' + i).wysihtml5();
i++;
};
self.removeNote = function (Note) {
self.Notes.remove(Note);
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.Notes), null, 2));
var jsondata = self.lastSavedJson();
$.ajax({
url: "/api/Notes/?mid=" + m + "&p=" + p,
cache: false,
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: jsondata,
success: function () {
alert("Success");
document.location.reload(true);
}
});
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new CreateNewNoteModel(initialData));
});
I am using jQuery validate plugin to add validation to knockout-js by using jQuery's validation methods: "$.validator.addMethod" and "$.validator.addClassRules".
Example:
First define your validation methods and css classes. Later on, we add the css classes to your inputs to validate your fields.
function DefineValidationRules() {
$.validator.addMethod("validateNumber", ValidateInteger, "This field is not a number");
$.validator.addMethod("validateRequired", $.validator.methods.required, "This field is required");
$.validator.addMethod("validateMin", $.validator.methods.min, $.format("This number be greater than or equal to {0}"));
$.validator.addMethod("validateMax", $.validator.methods.min, $.format("This number must be less than or equal to {0}"));
$.validator.addMethod("validateMinlength", $.validator.methods.minlength, $.format("This field must contain at least {0} characters"));
$.validator.addMethod("validateRangelength", $.validator.methods.rangelength, $.format("This field must contain between {0} and {1} characters"));
$.validator.addClassRules("validate-number", { validateNumber: true });
$.validator.addClassRules("validate-number-min", { validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required-number-min", { validateRequired: true, validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required", { validateRequired: true });
$.validator.addClassRules("validate-rangelengthmax6", { validateRangelength: [0,6] });
}
DefineValidationRules();
You can also add your own custom validation method:
function ValidateInteger(value) {
//do whatever you want to check
}
Having an input in knockout:
<input class="validate-required validate-number" type="text" data-bind="value: examplefield, valueUpdate: 'afterkeydown', attr: { attrname: 'itsvalue'}" />
Checking on submit:
$("#yoursubmitbutton").on("click", function () {
var formtosubmit = $("#idofyourform");
//check for validation errors
if (isValid(formtosubmit)) {
formtosubmit.submit();
//
// code to proceed to next step
}
});
function isValid(el) {
var $thisform = el;
$thisform.validate({
errorElement: "label",
errorPlacement: function (error, element) {
//eventual different error placing
if (element.attr("name") == "fname" || element.attr("name") == "lname") {
element.css("border", "2px solid red");
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
return $thisform.valid();
}

Send to and get value from a MVC3 controller by AJAX

I have a html input text field and a button.
I want to take user input value from that html text field by clicking that button and want to send that value (by AJAX) into a MVC3 Controller ( as like as a parameter of an ActionResult setValue() ) ?
An other thing i want to know that, how i can get a return value (that return by a ActionResult getValue() ) from a MVC3 Controller and set it in a html text field (by AJAX) ?
please help me with a good example, please. and sorry for my bad English. :)
Button click event
$(document).ready(function ()
{
$('#ButtonName').click(function ()
{
if ($('#YourHtmlTextBox').val() != '')
{
sendValueToController();
}
return false;
});
});
You call your ajax function like so:
function sendValueToController()
{
var yourValue = $('#YourHtmlTextBox').val();
$.ajax({
url: "/ControllerName/ActionName/",
data: { YourValue: yourValue },
cache: false,
type: "GET",
timeout: 10000,
dataType: "json",
success: function (result)
{
if (result.Success)
{ // this sets the value from the response
$('#SomeOtherHtmlTextBox').val(result.Result);
} else
{
$('#SomeOtherHtmlTextBox').val("Failed");
}
}
});
}
This is the action that is being called
public JsonResult ActionName(string YourValue)
{
...
return Json(new { Success = true, Result = "Some Value" }, JsonRequestBehavior.AllowGet);
}

fancybox: show partial view

I have the following js code:
function getSelectedPlace(form) {
var places = 1
$(form).find(":input").each(function () {
if ($(this).attr("name") === "Signed_Order_B64") {
$.ajax({
type: 'POST',
url: '/MyController/MyAction',
data: "id=" + places,
success: function (response) {
if (response.Result) {
ret = response.Message;
result = true;
$("input[type=hidden][name=email]").val(response.Email);
$("input[type=hidden][name=appendix]").val(response.Appendix);
} else {
// show fancybox
result = false;
}
},
error: function () {
result = false;
},
async: false
});
$(this).val(ret);
}
});
if (!result) {
$(submitButton).attr("value", btnText);
setStateFotBuyButton(false);
}
return result;
}
I have if statement in success block. I want show partial view in the fancybox in else block. How can I do this? Thanks
Not totally sure what you mean with "partial view" but you could do
} else {
$.fancybox(response,{
// fancybox options here
}); // fancybox
}
You could use the content switch which allows you to set the content of the fancybox to any html:
$.fancybox({
content: response
});

Resources