Passing FormCollection and FormData to controller [duplicate] - asp.net-mvc

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 7 years ago.
$("#btn2").click(function () {
var data = new FormData();
var Form = $("#form2").serialize();
var send = {FormData+&+ data};
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
data: send,
cache: false,
contentType: false,
processData: false
});
});
How to send FormData and Form object through ajax, please check the code its not working but it will tell you what I want to achieve
And also please mention how to receive this in Controller.
Basically I want to send picture and formcollection to my controller
Thanks

$("#btn2").click(function () {
var data = new FormData($('.form').get(0));
$.ajax({
url: '#Url.Action("AddProduct", "Product")',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false
});
});
Through googling I got this code but my controller still receiving null??
Controller
public void AddProduct(Product product, HttpPostedFileBase myImage){}

You can use form.serialize to send data to your controller.
$(document).ready( function() {
var form = $('#form2');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
} );

Related

Search2 - Ajax results with no search

I'm using ajax to pull in data from a php file (which returns json).
I'm wondering, can you have results pulled from Ajax and loads on click without having to search? so essentially you click the field, it drops down with all the elements from Ajax. Couldn't find in the documentation.
Code:
jQuery('.producttypesajax').select2({
allowClear: true,
placeholder: {
id: '',
text: 'Search by Product Type'
},
ajax: {
url: base + '/appProductTypeSearch.php',
dataType: 'json',
delay: 250,
data: function( params ) {
return {
q: params.term // search term
};
},
processResults: function( data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1
});
jQuery('.producttypesajax').on('select2:select', function (e) {
var data = e.params.data;
});
https://select2.org/data-sources/ajax
I believe there's no native solution for this, but I managed to do it somehow.
Since Select2 accepts Arrays as a data source, you can make an Ajax request returning your Json object and use it as an "Array".
Sample code:
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function (jsonObject){
$('#mySelect').select2({ data: jsonObject });
}
});
It worked for me. Hope it helps.

Send a CSV file from Ember Js to Rails using Ajax

I'm trying to upload a csv file with ajax from Ember Js and read it in my Rails application.
I've tried two different approaches. In the first one I tried to send the file from Ember like this:
submitImport() {
var fd = new FormData();
var file = this.get('files')[0];
fd.append("csv_file", file);
return this.get('authAjax')
.request('/contacts/import/csv', {
method: 'POST',
processData: false,
contentType: false,
data: fd
});
}
but the problem is that I don't get the csv_file param in the rails application. The request.content_type is application/x-www-form-urlencoded and I need multipart form. I could use reques.raw_post but then I get something like this ------WebKitFormBoundarymgBynUffnPTUPW3l\r\nContent-Disposition: form-data; name=\"csv_file\"; filename=\"elevatr_import.csv\"\r\nContent-Type: text/csv\r\n\r\ngeorgica,gica#me.com\nleo, leonard#yahoo.com\ngigel, becali#oita.fcsb\n\r\n------WebKitFormBoundarymgBynUffnPTUPW3l--\r\n and I would need to somehow parse this, and I don't really like this solution.
The other approach was to send the file base64 encoded and then decode it from Rails. I've tried this:
`
submitImport() {
var fd = new FormData();
var file = this.get('files')[0];
this.send('getBase64', file);
var encoded_file = this.get('encoded_file');
return this.get('authAjax')
.request('/contacts/import/csv', {
method: 'POST',
data: { csv_file: encoded_file }
});
},
getBase64(file) {
var controller = this;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
controller.set('encoded_file', reader.result);
};
}
But for some reason, the post request is submitted first and only after that the getBase64 method is called.
Does anyone knows why is this happening or if I should use a different approach?
Thanks
FormData
To send using multipart/form-data, you have the right idea and are setting the correct options, but it's possible that authAjax or something else is setting options that are causing a conflict, resulting in a content-type of application/x-www-form-urlencoded.
// this should make a request with a content-type of multipart/form-data
$.ajax({
url: 'upload/destination',
type: 'POST',
data: formDataObj,
contentType: false,
processData: false,
});
Base64
The reason your file is read after your request is made is that FileReader works asynchronously. To send as a base64 encoded string, you'll need to wait for the reader to complete before initiating your ajax request. You can do that by making your request after the onloadend event.
actions: {
submitImport() {
var file = this.get('files')[0];
this.encodeAndSendFile(file);
},
},
sendFile(base64File) {
return this.get('authAjax')
.request('/contacts/import/csv', {
method: 'POST',
data: { csv_file: encoded_file },
});
},
encodeAndSend(file) {
var controller = this;
var reader = new FileReader();
reader.onloadend = function () {
controller.sendFile(reader.result);
};
reader.readAsDataURL(file);
}

Ajax not allowing View rendering

I have a couple of variations on the ajax depending on the flow of interactions on the page. But it's only the variables that changes. here is one of them:
$('#btn_skickaEnkel').bind('click', function () {
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Nivå: $('#nivå').find(":selected").text(),
IsEnkel: true,
Telefon: $('#nr').val(),
ID: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
}
},
traditional: true
});
});
In my controller i am unable to redirect or return a different view. At this point the data from JSON is no longer relevant because it's already been saved to DB.
My Controller:
public ActionResult IntresseAnmälan(BokningContainer bokning)
{
db = new DbContext();
//Saving some data to database(removed)
//Just determening the state of container obj.
if (bokning.IsEnkel)
{
//Geting som information from db (removed)
//Creating a mail (removed)
email.Send(bokning.Namn, bokning.Mail, body);
}
else
{
}
//db.SaveChanges();
//This part is not working, I think it's beacuase of the Ajax
return View("IntresseAnmälan");
}
The view is not rendered and I think it's related to the ajax. The view is simply not rendered. Is there some way to force returning it and ignoring the ajax? As I said the data is no longer needed because the content is already saved to the DB.
You cannot render view on ajax call,simply you can use form post method or just redirect it to desired action on "succcess" of ajax call as below:
$('#btn_skickaEnkel').bind('click', function () {
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Nivå: $('#nivå').find(":selected").text(),
IsEnkel: true,
Telefon: $('#nr').val(),
ID: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
}
},
traditional: true,
success: function(result) {
window.location.href = '#Url.Action("action", "Controller")';
}
});
});
I couldn't believe my eyes when I figured out this "Bugg". The problem was that I, at some point, changed the submit to a button. So the form was never submiting. Well, at least I learnt a bit about views and Ajax.
Sorry for taking your time.

Making AJAX call to MVC API

I am trying to make an API call with ajax:
svc.authenticateAdmin = function (id, code) {
$.ajax({
url: 'api/event/authenticate',
data: { 'id': id, 'code': code },
datatype: 'json',
contentType: 'application/json',
type: 'GET',
success: function (data) {
App.eventBus.publish('authenticationComplete', data);
}
});
};
The method in the API Controller:
[ActionName("All")]
public bool Authenticate(int id, string code)
{
var repo = new MongoRepository<Event>(_connectionString);
var entry = repo.FirstOrDefault(e => e.Id == id);
return entry.AdminPassword == code;
}
But I am getting a 404 error: urlstuff/api/event/authenticate?id=123&code=abc 404 (Not Found)
I have copied the implementation from a number of known working calls (that I did not write). That look like:
svc.getEventFromCode = function (code) {
$.ajax({
url: '/api/event/',
data: { 'code': code },
dataType: 'json',
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedEvent', data);
App.eventBus.publish('errorEventCodeExists');
},
error: function () {
App.eventBus.publish('eventNotFound', code);
}
});
};
and
svc.getEventPage = function (pageNumber) {
$.ajax({
url: '/api/event/page/',
data: { 'pageNumber': pageNumber },
dataType: "json",
contentType: "application/json",
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedNextEventsPage', data);
}
});
};
But neither has to pass in 2 parameters to the API. I'm guessing it's something really minor :/
Your action name is called "Authenticate", but you have included the following which will rename the action:
[ActionName("All")]
This makes the URL
/api/event/all
The problem lies in your url.
Apparently, ajax interpret / at the start of the url to be root
When the application is deployed on serverserver, its URL is something like http://localhost:8080/AppName/
with api/event/page/, ajax resolve the URL to http://localhost:8080/AppName/api/event/page/ or an url relative to your current directory.
However, with /api/event/page/, the URL is resolved to http://localhost:8080/api/event/page/
Hope it helped.

Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:
$.post("/Journal/SaveEntry", JSONstring);
And here is the ajax method I tried:
$.ajax({
url: "/Journal/SaveEntry",
type: "POST",
data: JSONstring
});
Here is my Controller:
public void SaveEntry(string data)
{
string somethingElse = data;
}
For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?
Thanks very much.
UPDATE: It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:
$.post("/Journal/SaveEntry", { "jsonData": JSONstring });
Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:
public void SaveEntry(string jsonData)
and my post action in JS looks like:
$.post("/Journal/SaveEntry", { jsonData: JSONstring });
JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:
JSONstring = JSON.stringify(journalEntry); // journalEntry is my JSON object
So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.
Final Answer:
It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.
Actually, make sure youre using the
right key name that your serverside
code is looking for as well as per
Olek's example - ie. if youre code is
looking for the variable data then you
need to use data as your key. –
prodigitalson 6 hours ago
#prodigitalson, that worked. The
variable names weren't lining up. Will
you post a second answer so I can
accept it? Thanks. – Mega Matt 6 hours
ago
So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.
the data argument has to be key value pair
$.post("/Journal/SaveEntry", {"JSONString": JSONstring});
It seems dataType is missed. You may also set contentType just in case. Would you try this version?
$.ajax({
url: '/Journal/SaveEntry',
type: 'POST',
data: JSONstring,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
Cheers.
Thanks for answer this solve my nightmare.
My grid
..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();
<script type="text/javascript">
function onRowSelected(e) {
id = e.row.cells[0].innerHTML;
$.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
}
</script>
my controller
public ActionResult GridSelectionCommand(string id)
{
//Here i do what ever i need to do
}
The Way is here.
If you want specify
dataType: 'json'
Then use,
$('#ddlIssueType').change(function () {
var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlStoreLocation').get(0).options.length = 0;
$('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you do not specify
dataType: 'json'
Then use
$('#ddlItemType').change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("IssueTypeList", "SalesDept")',
data: { itemTypeId: this.value },
cache: false,
success: function (data) {
$('#ddlIssueType').get(0).options.length = 0;
$('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you want specify
dataType: 'json' and contentType: 'application/json; charset=utf-8'
Then Use
$.ajax({
type: 'POST',
url: '#Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlAvailAbleItemSerials').get(0).options.length = 0;
$('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again.");
}
});
If you still can't get it to work, try checking the page URL you are calling the $.post from.
In my case I was calling this method from localhost:61965/Example and my code was:
$.post('Api/Example/New', { jsonData: jsonData });
Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.

Resources