Getting NULL argument in MVC controller during Ajax post - javascript

I have an ajax post in which I send JSON string data, but I get null in my controller.
AJAX Call:
var jsonData = JSON.stringify(matrixPresenter);
$.post("/matrix/Savematrix?matrixData=" + jsonData , function (result) {
});
This is which I get when I keep my debugger on jsonData:
"{"tagList":[{"tagId":"16","name":"White","isEnable":"true"},{"tagId":"19","name":"Night","isEnable":"true"}],"captureCategoryTypeId":" 5051"}"
but when I keep debugger in my controller I see matrixData as null in
my Controller method:
[HttpPost]
public ActionResult Savematrix(string matrixData)
{
if (matrixData != null)
{
//do something
return null;
}
else
{
//do something
return null;
}
}
Looks like I am missing here something.

I think there might be a problem with the way you're constructing the JSON object for matrixPresenter. Could you please try replacing your view with the code below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnOK").click(function () {
var matrixPresenter =
{
tagList:
[
{ "tagId": "16", "name": "White", "isEnable": "true" },
{ "tagId": "19", "name": "Night", "isEnable": "true" }
],
captureCategoryTypeId: 5051
};
var jsonData = JSON.stringify(matrixPresenter);
$.post("/matrix/Savematrix?matrixData=" + jsonData, function (result) {
});
});
});
</script>
<input type="button" id="btnOK" value="OK" />

Related

Javascript validation - Check if a string is a correct object

I have a textarea where I need to put an object like that
[{
name: 'digitrust',
params: {
init: {
member: 'example_member_id',
site: 'example_site_id'
},
callback: function(digiTrustResult) {
if (digiTrustResult.success) {
var el = document.getElementById('dtidOutput');
console.log('Success', digiTrustResult.identity)
} else {
console.error('Digitrust init failed')
}
}
},
storage: {
type: 'html5',
name: 'pbjsdigitrust',
expires: 60
}
}]
I save this string in a mysql db and after I print it in a javascript object with php (laravel)
#if(!empty($useridobj))
try {
useridobj = {!! $useridobj !!};
if(typeof useridobj != 'object'){
useridobj = '';
}
} catch(err) {
useridobj = ''
}
#endif
If I put a correct obj in this textarea all works fine. But if I put something wrong like that
[{name:'digitrust',para]
console return an error.
So I'd like to validate the field first, in javascript (angular.js). I try something like that
if(!eval("var this_useridobj = "+ this.form.get("useridobj").value)){
this.form.get("useridobj").setErrors({ server: "UserId Object is not an object!" });
console.warn(this.form.get("useridobj"));
return false;
}
It doesn't work. Someone can help me please?
Thank u
Maybe you should validate in server side, eval or Function in the example above have some security issues, see this. Here you have a possible approach, but that Function executes anything:
document.getElementById("validate").addEventListener("click",()=>{
const json = document.getElementById("json").value;
const valid = (()=>{
try {
return (typeof (Function("return "+json))() === 'object')?true:false;
}
catch(error) {
return false;
}})();
console.log(valid)
});
//Try alert("something") in the textarea
<textarea id="json">{prop:[1,2,3}</textarea>
<button id="validate">
validate
</button>

two way data binding between view and controller mvc5

I am writing the web application which allows you to optimize SQL query.
I have such a view:
<div id="codeeditor" style="margin-right:20px; float:left" >
<script>
var editor = CodeMirror(document.getElementById("codeeditor"), {
mode: "sql",
theme: "dracula",
tabSize: 5,
lineNumbers: true,
});
editor.setSize(500, 500);
</script>
<input type="submit" value="start" id="btnClick" />
</div>
<div id="codeeditor1">
<script>
var editor1 = CodeMirror(document.getElementById("codeeditor1"), {
mode: "sql",
theme: "dracula",
tabSize: 5,
lineNumbers: true,
});
editor1.setSize("45%", 500);
</script>
</div>
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#btnClick").click(function () {
var f = {};
f.url = '#Url.Action("Demo", "Home")';
f.type = "POST";
f.dataType = "json";
f.data = JSON.stringify({ sourceSqlCode: editor.getValue() });
f.contentType = "application/json";
editor1.setValue(#ViewBag.readyQuery);
f.success = function (response) {
alert("success");
};
f.error = function (response) {
alert("err");
};
$.ajax(f);
});
});
</script>
}
Here is my controller which handles button clicking
[HttpPost]
public ActionResult Demo(string sourceSqlCodee)
{
//here I use my libraries and optimize query
ViewBag.readyQuery= optimizedQuery;
return View();
}
All I need Is to pass query to controller by clicking the button and pass it back to the view after modifying into the codeeditor1
It simply doesn't work because scripts are being run earlier than my controller method. How can I do that? Thanks!
I think you should just return a string in your controller action, like:
[HttpPost]
public string Demo(string sourceSqlCode)
{
//here I use my libraries and optimize query
return optimizedQuery;
}
Then, in your AJAX success method, do something like:
f.success = function (response) {
editor1.setValue(response);
};

performcallback gridview after combobox filtering

can you help me to fix my problem, I made gridview, and I use combobox to filter data in gridview and get gridview performcallback after filter, but gridview not callback after filter. how can I do ? Help me Please?
this is some code :
controller gridview filter :
[HttpPost]
public ActionResult FilterTypePro(String typePro)
{
//Session["typePro"] = typePro;
var model = Model._ProposalObject.ListDataProposal();
if (typePro != null && typePro != string.Empty)
{
model = Model._ProposalObject.ListDataProposal(typePro);
}
return PartialView("_gvPartialViewProposals", model);
}
and this is code to get value filter combobox :
function OnClickFilter(type) {
type = cbTypeProposal.GetValue();
$.ajax({
type: "POST",
cache: false,
async: false,
url: '#Url.Action("FilterTypePro", "App")',
data: { 'typePro': type },
success: function (data) {
/*gvPartialViewProposals.AdjustControl();
try {
gvPartialViewProposals.PerformCallback();
}
catch(er){
}*/
gvPartialViewProposals.Refresh(data);
}
});
}
and this is code to view cshtml :
groupItem.Items.Add(item =>
{
item.Caption = "Type Of Proposal";
item.Width = 400;
item.SetNestedContent(() =>
{
ViewContext.Writer.Write("<table><tr><td>");
Html.DevExpress().ComboBox(cmbSettings =>
{
cmbSettings.Name = "cbTypeProposal";
cmbSettings.Width = 100;
cmbSettings.Properties.DropDownStyle = DropDownStyle.DropDownList;
cmbSettings.ShowModelErrors = true;
cmbSettings.Properties.Items.Add("ATL", "ATL");
cmbSettings.Properties.Items.Add("BTL", "BTL");
cmbSettings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s, e) { OnClickFilter();}";
}).Render();
ViewContext.Writer.Write("</td></tr></table>");
});
}); ;
}).GetHtml();
I hope you can help me.
Modify your javascript function as follows:
function OnClickFilter(type){
type = cbTypeProposal.GetValue();
gvPartialViewProposals.PerformCallback({
'typePro': type
});
}
Modify your grid settings as follows:
settings.Name = "gvPartialViewProposals";
settings.CustomActionRouteValues = new { Controller = "App", Action = "FilerTypePro" };

Parsley Remote and Server Side Validation (can't get content from json object)

I am trying to validate if an email already exists in our database. I always get a 200 status code from the Ajax Request, but I get the body of the request that looks like this. Result =1 if that email does not exists and is available (the form should return true) and Result = 0 if that email already exists in the database (the from should return false and not validate). However I keep geting data undefined in the console. Seems like I don't know how to pass the json object to the function.
I'll buy a beer to anyone that can help me figure this out. Thank you.
JSON RESPONSE
id: "1c29da8e-ca94-4ea4-a69f-f0af15f54bf5", redirectPage: "/public/actionStatus.jsp", errorText: "",…}
action: "/check.douserEmailAvailable"
data: {}
errorCode: ""
errorText: ""
id: "1c29da8e-ca94-4ea4-a69f-f0af15f54bf5"
redirectPage: "/public/actionStatus.jsp"
result: "1"
text1: ""
text2: ""
text3: ""
text4: ""
text5: ""
JQUERY and HTML
$(document).ready(function(){
window.Parsley.addAsyncValidator('mycustom', function (data) {
if (data.result == 1) {
console.log("does not exist");
return true;
} else {
console.log("already exist");
return false;
}
}, '/check.do?action=userEmailAvailable&ajax=1');
$('#userReg').parsley();
});
<input type="email" name="userEmail1" data-parsley-remote data-parsley-remote-options='{ "type": "POST", "data": { "token": "value" } }' data-parsley-remote-validator='mycustom' id="userEmail1" value="" required />
The first argument passed to your asynch validator is xhr, not data.
You can use $.parseJSON(xhr.responseText), or xhr.done(function(json){...}), etc... to do what you are trying to do.
Got it working, If anyone has issues in the future.
$(document).ready(function(){
window.Parsley.addAsyncValidator('emailvalidation', function (data) {
var myResponseText = data.responseText;
var obj = jQuery.parseJSON(myResponseText);
if (obj.result == 1) {
return true;
} else {
return false;
}
}, '/check.do?action=userEmailAvailable&ajax=1');
$('#userReg').parsley().on('form:success', function() {
var formData = $("#userReg").serializeArray();
var action = "<%=pdo.getRegistrationData().registrationType.toString()%>";
$.post("/userRegistration.do?action="+ action +"&ajax=1", formData,
function(data) {
window.location.href = data.redirectPage;
});
});
});

Select2 limit number of tags

Is there a way to limit the number of tags a user can add to an input field using Select2?
I have:
$('#tags').select2({
containerCssClass: 'supplierTags',
placeholder: "Usual suppliers...",
minimumInputLength: 2,
multiple: true,
tokenSeparators: [",", " "],
placeholder: 'Usual suppliers...',
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.name.localeCompare(term) === 0;
}).length === 0) {
return {id: 0, name: term};
}
},
id: function(e) {
return e.id + ":" + e.name;
},
ajax: {
url: ROOT + 'Call',
dataType: 'json',
type: 'POST',
data: function(term, page) {
return {
call: 'Helpers->tagsHelper',
q: term
};
},
results: function(data, page) {
return {
results: data.tags
};
}
},
formatResult: formatResult,
formatSelection: formatSelection,
initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
name: item[1]
});
});
callback(data);
}
});
It would be great if there could be/is a simple parameter like limit: 5 and a callback to fire when the limit is reached.
Sure, with maximumSelectionLength like so:
$("#tags").select2({
maximumSelectionLength: 3
});
Maximum Selection Length
Select2 allows the developer to limit the number of items that can be
selected in a multi-select control.
http://ivaynberg.github.io/select2/
It has no native callback, but you can pass a function to formatSelectionTooBig like this:
$(function () {
$("#tags").select2({
maximumSelectionLength: 3,
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
});
http://jsfiddle.net/U98V7/
Or you could extend formatSelectionTooBig like this:
$(function () {
$.extend($.fn.select2.defaults, {
formatSelectionTooBig: function (limit) {
// Callback
return 'Too many selected items';
}
});
$("#tags").select2({
maximumSelectionLength: 3
});
});
Edit
Replaced maximumSelectionSize with the updated maximumSelectionLength. Thanks #DrewKennedy!
method 1
$("#tags").select2({
maximumSelectionLength: 3
});
method 2
<select data-maximum-selection-length="3" ></select>
list of all available options https://select2.org/configuration/options-api
The accepted answer doesn't mention that the maximumSelectionLength statement should be inside the document.ready function. So for anyone who is having the same trouble I did, here is the code that worked for me.
$(document).ready(function() {
$("#id").select2({
maximumSelectionLength: 3
});
});
$("#keywords").select2({
tags : true,
width :'100%',
tokenSeparators: [','],
maximumSelectionLength: 5,
matcher : function(term,res){
return false;
},
"language": {
'noResults': function(){
return "Type keywords separated by commas";
}
}
}).on("change",function(e){
if($(this).val().length>5){
$(this).val($(this).val().slice(0,5));
}
});
Try like this. It'll short up to 5 keywords.
This is not working for me, I am getting query function not defined for Select2, so here is another workaround.
var onlyOne=false;
$("selector").select2({
maximumSelectionSize:function(){
if(onlyOne==true)
return 1;
else
return 5;
}
});
This setting can be defined as function and it's called every time you start searching something.
Important thing is that you have something defined outside this select2 closure so you can check it (access it). In this case you could somewhere in your program change value of onlyOne and of course this returned limit can also be dynamical.
This is working for me.
$("#category_ids").select2({ maximumSelectionLength: 3 });
Send the Get Request to action method and the Map the class properties to drop down id and text property
$("#DropDownId").select2({
minimumInputLength: 3,
maximumSelectionLength: 10,
tags: [],
ajax: {
url: "#Url.Action("ActionName", "ControllerName")",
type: "get",
dataType: 'json',
delay: 250,
data: function (params) {
return {
Title: params.term // search term
};
},
processResults: function (response) {
return {
results: $.map(response, function (item) {
return {
text: item.Title,
id: item.Id
}
})
};
}
}
});
Action Method
[HttpGet]
public JsonResult ActionName(string Title)
{
ClassName obj= new ClassName ();
obj.Title = "PMPAK";
obj.Id= -1;
obj.Add(nibafInstitute);
return Json(obj, JsonRequestBehavior.AllowGet);
}
public class ClassName
{
public int Id{ get; set; }
public string Title { get; set; }
}

Categories

Resources