JQuery FormData Get/Post - c#

Im tring to post FormData values to controller. Its success on POST method but i want to get returned values. I tried get but dont work. I added too many argument but dont work. Can u help me ?
jquery/ajax
var Data = new FormData();
Data.append('yparca', yparca);
Data.append('mekanik', mekanik);
//more values
$.each($("#img_upload_" + id)[0].files, function (i, file) {
Data.append('resimler', file);
});
$.ajax({
url: "/Sections/AddRowsToMarketPart",
type: 'GET',
data: Data,
processData: false,
contentType: "application/json; charset=utf-8",
dataType:'json',
success: function (data) {
alert("success");
Toast.fire({
icon: 'success',
title: 'Parça sepete eklendi.'
})
}
Controller
[HttpGet]
public JsonResult AddRowsToMarketPart(SubPart2Val model)
{
//Do something AND RETURN A VALUE
return Json(model);
}
Class
public class SubPart2Val
{
public int id { get; set; }
public string yparca { get; set; }
public string mekanik { get; set; }
//some properties
public List<IFormFile> resimler { get; set; }
}

Your content type is incorrect, you set it as json when it's form data.
To have it set properly in $.ajax set contenType to false
Also you cant sent form data with a GET request use POST
$.ajax({
url: "/Sections/AddRowsToMarketPart",
type: 'POST',
data: Data,
processData: false,
contentType: false,
dataType:'json',
...
[HttpPost]
public JsonResult AddRowsToMarketPart(SubPart2Val model)
{
//Do something AND RETURN A VALUE
return Json(model);
}

Related

jQuery Array is not posting to ASP.NET MVC controller

I am having a hard time posting a list of arrays from my view to the controller. Every other value is coming through.
Can someone spot what is wrong with my code?
Controller:
public ActionResult SaveProgress(BBCRMSurveyVM model)
{
try
{
return Json(new { success = true });
}
catch (Exception e)
{
return Json(new { success = false, msg = e.Message });
}
}
Main view model:
public string ImplementationProcessFeelWasSuccessful { get; set; }
public string ImplementationProcessAdviceOtherFederations { get; set; }
public List<AdditionalTechnologyVM> AdditionalTech = new List<AdditionalTechnologyVM>();
AdditionalTechVM:
public class AdditionalTechnologyVM
{
public string PlatformName { get; set; }
public string BusinessPurpose { get; set; }
public bool? FullyIntergrated { get; set; }
public bool? PartiallyIntergrated { get; set; }
}
JS file:
function onAddButtonClickEvent() {
additionaltechs.push({
'PlatformName': platformNameAT,
'BusinessPurpose': businessPurposeAT,
'FullyIntergrated': intergrated == "Fully" ? true : false,
'PartiallyIntergrated': intergrated == "Partially" ? true : false
});
}
function SaveProgress() {
var formData = $('#wizard').serializeArray();
//if (additionaltechs.length > 0) {
// for (var x = 0; x < additionaltechs.length; x++) {
// formData[formData.length] = { name: "AdditionalTech", value: JSON.stringify(additionaltechs[x]) };
// }
//}
formData[formData.length] = { name: "AdditionalTech", value: additionaltechs };
$.each(formData, function (index, field) {
if (field.name.search('Budget') > 0) {
field.value = field.value.replace('$', '').replace(/,/g, '');
}
});
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
The output in the console:
The list count is always 0?
I think you made this more complicated than you needed it to be. :)
Ultimately, it looks like your controller method is taking a single model, not an array. Thus, I would suspect to see the JSON you send look like this:
{
"ImplementationProcessFeelWasSuccessful" : "",
"ImplementationProcessAdviceOtherFederations" : "",
"AdditionalTech" : [...]
}
If it should be a single item being sent, then I'd expect your code to be like this:
function SaveProgress() {
var formData =
{
ImplementationProcessFeelWasSuccessful : $('#wizard #val1').val(),
ImplementationProcessAdviceOtherFederations : $('#wizard #val2').val(),
AdditionalTech : additionaltechs
};
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
However, you are sending an array of items up and that makes no sense here.
Ended up sending the list as a JSON string & receiving it also as a string. In the controller I using the JsonConvert.DeserializeObject method like this:
var additionalTechs = JsonConvert.DeserializeObject<List<AdditionalTechnologyVM>>
(model.AdditionalTech);

pass parameter and model from ajax

I am using ajax for the request I am passing a parameter key and a model to controller method but I can get the key on the method but getting the model value is always null when I am setting the traditional value true and 0 when I am sending it without traditional.
Here is my ajax method.
$('.search-hot-destination').on('click', '.rightdesti-list > a', function () {
var key = $(this).parents('li').find('.countryNameList').attr('id');
var model ={
DestinationCityID: $(this).attr('id')
}
$.ajax({
type: "GET",
url: "/Home/destination",
data: {key: key, model:model},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('hello');
}
})
});
Here is my controller method.
public ActionResult destination(string key, FilterDataViewModel model, string searchingkey, int skip = 0)
{
}
Here is my Model.
public class FilterDataViewModel
{
public int ItemID { get; set; }
public string SearchingKey { get; set; }
public int DestinationCityID { get; set; }
public int citykey { get; set; }
}
In your ajax request you should JSON.stringify(Object);
data: JSON.stringify({key: key, model:model}),

Send object to mvc controller using ajax

I am passing multiple parameters in an object and then passing it to a Method in the controller. It is hitting the method but it's not carrying the data to be sent from ajax call to the method . When I am going to check object of the model it displays null. SO can I send the data in such a way or should I try another approach?
Thanks in advance Please help me.
Here is my code.
var Color = [], Material = [], Size = [], FinishingType = [], Style = [];
$('.productFilterLabelList .filterList').on('change', '[type=checkbox]', function () {
debugger;
var Main = {};
var filterType = $(this).parents('.productFilterLabelList').find('.hdn-filter-type').val();
var filterTypeID = $(this).val();
var ischeked = $(this).is(':checked');
if (ischeked) {
if (filterType == 'color') {
Color.push(filterTypeID);
}
else if (filterType == 'size') {
Size.push(filterTypeID);
}
else if (filterType == 'finsih') {
FinishingType.push(filterTypeID);
}
else if (filterType == 'material') {
Material.push(filterTypeID)
}
else {
Style.push(filterTypeID);
}
}
else {
alert('hello');
if (filterType == 'color') {
Color.pop(filterTypeID);
}
else if (filterType == 'size') {
Size.pop(filterTypeID);
}
else if (filterType == 'finsih') {
FinishingType.pop(filterTypeID);
}
else if (filterType == 'material') {
Material.pop(filterTypeID)
}
else {
Style.pop(filterTypeID);
}
}
Main = {
Color: Color,
Size: Size,
FinishingType: FinishingType,
Material: Material,
Style: Style
}
console.log(Main);
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
data: '{Main:' +JSON.stringify(Main)+' }',
success: function (results) {
}
})
});
public ActionResult SearchByAllFilterTags(ProductFilterViewModel Main)
{
return Json("", JsonRequestBehavior.AllowGet);
}`public class ProductFilterViewModel
{
public int[] Color { get; set; }
public int[] Material { get; set; }
public int[] Size { get; set; }
public int[] FinishingType { get; set; }
public int[] Style { get; set; }
public int[] Pattern { get; set; }
//public string FilterText { get; set; }
//public List<ProductFilterViewModel> FilterTextList { get; set; }
}`
You don't need to stringify your object. Just pass your Main object:
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
traditional: true,
data: Main,
success: function (results) {
}
})
Edit:
If your arrays are empty in the action method try to add traditional: true to ajax settings
You do not need to stringify. Use this format:
Main = {
"Color": [{Color}],
"Size": [{Size}],
"FinishingType": [{FinishingType}],
"Material": [{Material}],
"Style": [{Style}]
}
console.log(Main);
$.ajax({
url: '/Home/SearchByAllFilterTags',
type: "Get",
contentType: "application/json",
dataType: "json",
data: Main,
success: function (results) {
}
})
});
As long as you didn't add quotation marks in your json data, your data will not pass.
This will work if your model at the controller is matched.

asp mvc controller receiving null values from ajax

have tried the methods found but still cannot seem to tackle the issue.
am passing a list of object via Jquery Aja but it seems that the controller is receiving null values (it is recognizing the list count fine).
the jquery code is as follows:
var xmlids = Array();
for (var i = 0; i < orderId.length; i++) {
var xdata = {
"XmlOid": "" +orderId[i] + "",
"CourierCompany": $("#CourierCompany_"+orderId[i]).val() ,
"CourierService": $("#CourierService_" + orderId[i]).val(),
"StoreId" : storeId
};
xmlids.push(xdata);
}
var data = { invoices: xmlids };
$.ajax({
url: purl,
type: "POST",
dataType: "json",
//contentType: "application/json;",
async: false,
data: data,
The controller param is :
public JsonResult ProcessSaleOrder(List<XMLInvoiceGeneration> invoices)
the object is as follows:
public class XMLInvoiceGeneration
{
public Int64 XmlOid { get; set; }
public string CourierCompany { get; set; }
public string CourierService { get; set; }
public Int64? StoreId { get; set; }
}
any help appreciated.
I tried to replicate your problem.
I created a new ASP.NET MVC web application, and in the Home controller's Index view, I added the following
<input type="button" id="send" value="Send" />
#section scripts{
<script type="text/javascript">
$(function () {
$("input#send").on("click", function () {
var xmlids = Array();
for (var i = 0; i < 2; i++) {
var xdata = {
"XmlOid": 1,
"CourierCompany": "TempData",
"CourierService": "Temp",
"StoreId": 2
};
xmlids.push(xdata);
}
var data = { invoices: xmlids };
$.ajax({
url: "/Home/ProcessSaleOrder",
type: "POST",
dataType: "json",
async: false,
data: data
});
});
})
</script>
}
I basically created some temp data, but trying to still use your original idea. My controller looks like this:
[HttpPost]
public ActionResult ProcessSaleOrder(List<XMLInvoiceGeneration> invoices)
{
return new EmptyResult();
}
When I click the button, and hit the breakpoint in the controller, the invoices parameter contains 2 items, both with the values I set in the JavaScript code. I'm not sure why your code isn't working, but maybe you can use mine as a template to help you narrow down what the issue is.
Try this
uncomment //contentType: "application/json;",
And send data with JSON.stringify(data)
data: JSON.stringify(data)
PS: Best practice for url : url: "#Url.Action("method","controller")"
I had the same issue on sending a List to the controller. After a lot of effort, I found the reason why it is sending as null. It's the fields with Return Type(Class) that are not added with {get; set; }
$.ajax({
url: "/Home/CreateTasks",
data: ko.toJSON({Id: this.Id, tasks: objList }),
type: "POST",
dataType: "json",
processData: true,
contentType: "application/json; charset=utf-8",
success: data => {
}
And my Model Class is:
After
public class TaskFields
{
public string Title { get; set; }
public string Activity { get; set; }
}
public class CreateTaskInput
{
public int Id { get; set; }
public TaskFields TaskProperties { get; set; }
}
Before it was:
public class TaskFields
{
public string Title;
public string Activity;
}
public class CreateTaskInput
{
public int Id;
public TaskFields TaskProperties;
}
And My Controller Method is:
[HttpPost]
public JsonResult MethodName(int Id, List<CreateTaskInput> tasks)
{
}
I am not sure this answer will help you. But it may help someone who has a similar mistake. Thanks!
Add [FromBody] to the parameters in action
[HttpPost]
public ActionResult ProcessSaleOrder([FromBody] List<XMLInvoiceGeneration> invoices)
{
return new EmptyResult();
}

Jquery Ajax json Serializable

I am learing using jquery ajax to hander the JSON..i writre a demo code.
HTMLCODE
$(function () {
$("#add").click(function () {
var json = '{ "str":[{"Role_ID":"2","Customer_ID":"155","Brands":"Chloe;","Country_ID":"96;"}]}';
$.ajax({
url: "func.aspx/GetJson",
type: "POST",
contentType: "application/json",
dataType: 'json',
data: json,
success: function (result) {
alert(result);
},
error: function () {
alert("error");
}
});
});
});
<div>
<input type="button" value="add" id="add" />
</div>
i got a input and bind a script function to it, now the proble is comeing..
my C# functiong like that.
[WebMethod]
public static string GetJson(object str)
{
return str.ToString();//good for work
}
[Serializable]
public class TestClass
{
public TestClass()
{
}
public TestClass(string role_id, string customer_id, string brands, string countryid)
{
this.Role_ID = role_id;
this.Customer_ID = customer_id;
this.Brands = brands;
this.Country_ID = countryid;
}
public string Role_ID { get; set; }
public string Customer_ID { get; set; }
public string Brands { get; set; }
public string Country_ID { get; set; }
}
when i user
public static string GetJson(object str)
everything is so good.~~ no error at all
but . when i try to use my own class TestClass.
firebug tell me that
"Type 'TestClass' is not supported for deserialization of an array."
.any body can give me help:XD
This is how it looks when I do this using a WCF webservice. Hopefully it can help you. Let me know if you need any further clarification.
Script:
var data = {
emailAddress: emailAddress,
firstName: firstName,
lastName: lastName,
groups: groups
};
$.ajax({
type: "POST",
url: Client.svc/Subscribe",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json; charset=utf-8",
processdata: true,
success: function (result) {
//do something
}
});
Service:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[BasicHttpBindingServiceMetadataExchangeEndpoint]
public class Client : IClient
{
public bool Subscribe(string emailAddress, string firstName, string lastName, string[] groups)
{
//do something
return true;
}
}

Categories

Resources