Sending Large data from View to Controller in MVC - javascript

I am getting table records, I need to send it to Controller so that I can send email. When I tried with following code, it's throwing error
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "GET",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
data: "{'emailList': '" + JSON.stringify(emailList) + "', body' : '" + body + "' }",
success: function (json) {
alert(json);
}
});
Error as : HTTP Error 404.15 - Not Found The request filtering module
is configured to deny a request where the query string is too long.
Most likely causes: Request filtering is configured on the Web server
to deny the request because the query string is too long.
I have tried to add following code, still same error
var formData = new FormData();
var objArr = [];
objArr.push({ "emIl": emailList, });
//JSON obj
formData.append('objArr', JSON.stringify(objArr))
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "POST",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
processData: false,
contentType: false,
data: formData,
Here is Controller Code
[HttpGet]
public JsonResult GetFinanceSendMail(string emailList, string body)
{
List<string> emails = emailList.Split(',').ToList();
// Send Email add optiona arg to the method
_openPobl.TriggerFinanceEmail(body, emails);
return Json(emails, JsonRequestBehavior.AllowGet);
}

fix the action, remove [get]
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(string emailList, string body)
and ajax
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
var body = 'Hi Team';
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: {emailList: emailList, body : body },
success: function (json) {
alert(json);
}
});
but if you want to use post much more reliable to create a viewmodel class
public class ViewModel
{
public string EmailList {get;set;}
public string Body {get;set;}
}
action
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(ViewModel model)
.....
and ajax
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: { model: {emailList: emailList, body : body } },
success: function (json) {
alert(json);
}
});

Related

Return parameter null in controller from ajax

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)
{
.......
}

C# Leaflet how do i properly post data from view to controller using ajax?

currently i keep getting the alert request failed whenever i try to pass back data from view to controller.
leafletLats and leafletLngs are an array, but im not sure of the datatype. They are derived from coord which is of type LatLng[].
may i know what is causing the Post method to not pass through? is it the problems in the controller?
in View
routeControl.on('routeselected', function (e) {
var coord = e.route.coordinates;
var name = e.route.name;
var leafletLats = coord.map(function(point) {
return [point.lat];
});
var leafletLngs = coord.map(function(point) {
return [point.lng];
});
alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLats);
alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLngs);
//alert('Array size = ' + coord.length + '\nCoordinates: \n' + coord.join('\n'));
$.ajax({
type: 'Post',
url: '/Map/GetRouteCoordinates',
data: JSON.stringify(leafletLats),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(`Request passed!`);
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(`Request failed!`);
}
});
in controller
[HttpPost]
public ActionResult GetRouteCoordinates(MyModel test)
{
//do something with the result
Debug.WriteLine("data passed back");
return View();
}
public class MyModel
{
public List<MyModel_Value> latList { get; set; }
}
public class MyModel_Value
{
public double lat { get; set; }
}
did some modification and changing the data to data: JSON.stringify({ arr: stringifiedArr }) works for me

Passing an array Of Objects Into An MVC .net core Controller Method Using jQuery Ajax

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

How to send and receive ajax request with parameter in Spring Framework?

I'm try to send a request with ajax but have status 400 bad request.
what kind of data should i send and how to get data in controller?
I'm sure that request is fine only the parameter go wrong
jsp
<script type="text/javascript">
var SubmitRequest = function(){
$.ajax({
url : "submit.htm",
data: document.getElementById('inputUrl'),
type: "POST",
dataType: "text",
contentType: false,
processData: false,
success :
function(response) {
$('#response').html(response);
}
});
}
</script>
controller
#RequestMapping(value = "/submit", method = RequestMethod.POST)
public #ResponseBody
String Submit(#RequestParam String request) {
APIConnection connect = new APIConnection();
String resp = "";
try {
resp = "<textarea rows='10'cols='100'>" + connect.doConnection(request) + "</textarea>";
} catch (Exception e) {
// TODO Auto-generated catch block
resp = "<textarea rows='10'cols='100'>" + "Request failed, please try again." + "</textarea>";
}
return resp;
}
To send an Ajax post request, you could use this :
$.ajax({
type: "POST",
url: "submit.htm",
data: { name: "John", location: "Boston" } // parameters
})
And in Spring MVC the controller:
#RequestMapping(value = "/submit.htm", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
String Submit(#RequestParam("name") String name,#RequestParam("location") String location) {
// your logic here
return resp;
}

How to Parse Collection in JQuery

I have a IEnumerable Collection of Custom DataType that I'm sending to the Client.
I want to parse the collection in my JQuery method. Currently I'm getting value as "undefined". Below is my code:
Service:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<CustomData> GetSetting(long userId);
public IEnumerable<CustomData> GetSetting(long userId)
{
var tempData = Context.DialogSettings.Where(item => item.id == userId).ToList();
return tempData.Select(dialogSetting => new CustomData { KeyName = dialogSetting.KeyName, KeyValue = dialogSetting.KeyValue }).ToList();
}
[DataContract]
public class CustomData
{
[DataMember]
public String KeyName;
[DataMember]
public String KeyValue;
}
Client:
function LoadSetting() {
$.ajax({
type: "GET",
url: "SampleService.svc/GetSetting",
data: '{"userId": "' + 1 + '"}',
processData: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myHistoryList = data.d;
alert(myHistoryList); // here I'm getting value: undefined
},
error: function (result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}
});
}
});
From the comments on the question I can safely presume that the following js code will work:
if(typeof data != 'undefined'){
alert(data[0].KeyName); //this will yield a value.
}
else
alert('Ok. This is weird');

Categories

Resources