I am returning array of strings from controller to ajax call. trying to set to textbox those values. in textbox it is not populating. but I can see data in success method.
[HttpGet]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult GetWorkNamesAutoPoplate(string companyName)
{
...
var newKeys = companyNameslst.Select(x => new string[] { x }).ToArray();
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
}
JS
$(document).on('change', '[name="FindCompanyName"]', function () {
$('[name="FindCompanyName"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "GetWorkNamesAutoPoplate",
type: "GET",
dataType: "json",
data: { companyName: $('[name="FindCompanyName"]').val() },
success: function (data) {
alert(JSON.stringify(data));
response($.map(data, function(item) {
console.log(item);
return {
value: item
}
}));
}
});
},
messages: {
noResults: "", results: ""
}
});
});
alert(JSON.stringify(data)); display like this.
How to populate this data in textbox
The return type of your json is an array of arrays, i think you should return it as an array
var newKeys = companyNameslst.ToArray();
also, your data are serialized twice,
one from line,
var json = JsonConvert.SerializeObject(newKeys);
and second time from JsonResult action filter
return Json(json, JsonRequestBehavior.AllowGet);
sending json data like,
return Json(newKeys, JsonRequestBehavior.AllowGet);
instead of
var json = JsonConvert.SerializeObject(newKeys);
return Json(json, JsonRequestBehavior.AllowGet);
should work.
hope this helps.
This may resolve your issue :
success: function (data) {
alert(JSON.stringify(data));
if (data != null) {
response(data.d);
}
}
Also this link might help you to get some information :How to use source: function()... and AJAX in JQuery UI autocomplete
Related
I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}
I am trying to submit a form via ajax like this:
$(document).ready(function () {
$("#form").submit(function (e) {
e.preventDefault();
var token = $('input[name="__RequestVerificationToken"]', this).val();
var form_data = $(this).serialize();
$.ajax({
url: "#Url.Action("SaveRole", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: form_data,
contentType: "application/json",
success: function (result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
return false;
console.log(form_data);
});
});
This contacts this controller:
[HttpPost]
[ValidateAjax]
[ValidateAntiForgeryToken]
public ActionResult SaveRole(SaveRolesDetailsViewModel Input)
{
//var role = rolesData.GetByName(Input);
var result = this.Json(new
{
Output = Input
}, JsonRequestBehavior.DenyGet);
return result;
}
Right now, I'm getting errors that my RequestVerificationToken field is not being submitted but I'm not sure how I can combine it with my form data. By default, when I serialize my form data, it already sends this token but for some reason my controller still fails it.
Also, how do I use the modelstates to show my form validations? Right now they are returned as json objects.
EDIT:
AjaxValidate Attribute:
public class ValidateAjax : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}
When I submit an empty form, this is what is returned:
0:{key: "RoleName", errors: ["The Role Name field is required."]}
When you use the jQuery .serialize() method, it generates query string format (i.e. ..&name=value&..., which needs to be sent using the default contentType - i.e 'application/x-www-form-urlencoded; charset=UTF-8'.
Remove the contentType: "application/json", from the ajax options.
In addition, your var token = $('input[name="__RequestVerificationToken"]', this).val(); line of code is not necessary - the token is included when you use .serialize()
$("#form").submit(function (e) {
e.preventDefault();
// Add the following if you have enabled client side validation
if (!$(this).valid()) {
return;
}
var form_data = $(this).serialize();
$.ajax({
url: "#Url.Action("SaveRole")",
method: "POST",
data: form_data,
success: function (result) {
... // see notes below
},
error: function (error) {
console.log(error);
}
});
// return false; not necessary since you have used e.preventDefault()
console.log(form_data);
});
To return ModelState errors, remove your ValidateAjaxAttribute - returning a BadRequest is not appropriate (which is intended to indicate that the server could not understand the request due to invalid syntax).
Instead modify the POST method to return a JsonResult that includes the errors (note there is no need to return the model)
public ActionResult SaveRole(SaveRolesDetailsViewModel Input)
{
if (ModelState.IsValid)
{
return Json(new { success = true });
}
else
{
var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });
return Json(new { success = false, errors = errors });
}
}
Then in the success callback, if there are errors, loop through them and find the corresponding <span> element generated by your #Html.ValidationMessageFor() and update its contents and class names
success: function (result) {
if (result.success) {
return;
}
$.each(result.errors, function(index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
},
am using .netcore 1.1 , Visual studio 2017 , Jquery version = "3.2.1"
,am trying to make the MVC controller to get data from my page ,
i have 2 arrays in java , one is an array of Object (model view) and one is an array of strings
objects array always return error 400 (bad request)
2- string array ,always send null to the controller
i followed the below answers with no success
https://stackoverflow.com/a/13255459/6741585
and
https://stackoverflow.com/a/18808033/6741585
below is my chtml page
//#region send data back t oserver
$('#Savebtn').click(function () {
console.log(editedRows);
var UpdatedRows = JSON.stringify({ 'acActivityed': editedRows });
console.log(UpdatedRows);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/Edit",
//traditional: true,
data: UpdatedRows ,
dataType: "json",
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
//#endregion
//#region deleted all selected
$('#DeleteSelectedbtn').on('click', function () {
if (confirm("Are you sure to delete All Selected ?????")) {
var selectedData = [];
var selectedIndexes;
selectedIndexes = grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(grid.getDataItem(value).id);
});
console.log(selectedData);
var SelectedIds = selectedData.join(',') ;
console.log(SelectedIds);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/DeleteSelected",
data: JSON.stringify({ "ids": SelectedIds }),
dataType: "json",
success: function (data) {
grid.render();
},
error: function (err) {
alert("error : " + err);
}
});
}
});
//#endregion
and both do have data as below console shots
the selected ID's one
my Controller
this one should expect the list of object and always return bad request ,
[HttpPost]
[ValidateAntiForgeryToken]
//public jsonResult Edit( List<acActivitytbl> acActivityed)
public ActionResult Edit( List<acActivitytbl> acActivityed)
{
foreach (acActivitytbl it in acActivityed)
{
logger.Log(LogLevel.Info, it.ID);
logger.Log(LogLevel.Info, it.Name);
logger.Log(LogLevel.Info, it.IsActive);
}
//return View(acActivityed);
return Json(new { success = true, responseText = "end of Page" });
}
that one should expect the delimited string ,but always receive null
public ActionResult DeleteSelected(string ids)
{
try
{
char[] delimiterChars = { ' ', ',', '.', ':', ' ' };
string[] words = ids.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
if (words != null && words.Length > 0)
{
foreach (var id in words)
{
bool done = true; //new acActivitiesVM().Delete(Convert.ToInt32(id));
logger.Log(LogLevel.Info, " acActivities ID {0} is Deleted Scussefully ", id);
}
return Json(new { success = true, responseText = "Deleted Scussefully" });
}
return Json(new { success = false, responseText = "Nothing Selected" });
}
catch (Exception dex)
{
..... removed to save space
});
}
}
i know there is something missing here ,but i cannot find it ,any help in that ??
I want to pass the element's value into a controller
JavaScript:
var element = document.getElementById("valueSelected");
Query String
Document.location="/ControllerName/ActionName/Value";
Ajax
$.Post('/ControllerName/ActionName/',{Parameter: element});
No problem
Script
function Delete() {
$.getJSON("/ControllerName/ActionName/", {Id : Value}, function (data)
{
alert(data)
})
};
C#
public JsonResult ActionName(int? id)
{
string Data = "Sample Data";
return Json(Data, JsonRequestBehavior.AllowGet);
}
Let suppose Home is your Controller.
Add a function in your controller who can handle your ajax request. Suppose function name is getValue:
public void GetValue(string elementValue)
{
//add your controller logic here
}
In your javascript, I use jquery to perform ajax request, you need to jquery to do this so:
var element = document.getElementById("valueSelected");
$.ajax({
type: "POST",
data : { elementValue : $(element).val() },
url: '#Url.Action("GetValue", "Home")'
}).done(function (data) {
console.log('done');
});
I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});