How to upload recorded audio (recorder.js-master) through MVC Controller? - asp.net-mvc

I've been working with a great audio recorder which is recorder.js-master.
But I can't make the upload work with MVC Controller.
Here's my javascript function.
function AudioUpload(title, description) {
Recorder.upload({
method: "POST",
url: '#Url.Action("Upload", "Audio")',
audioParam: "Recording",
params: {
"Title": title,
"Description": description
},
success: function (responseText) {
alert(responseText.Success);
},
error: function () {
alert("error");
},
progress: NULL
});
}
Here's my AudioController
public JsonResult Upload(VoicePassage passage)
{
//upload Audio
return Json(new { Success = true });
}
I have a breakpoint in Upload just to know that it's going to my Controller but it doesn't.
Please help.
Here's the reference I follow. http://marc.codewisp.com/2013/05/07/in-browser-audio-recording-recorder-js-asp-net-mvc/?replytocom=12#respond
Regards,
Christian

I'm the author of the original post you linked to.
A few things to try out:
Add a breakpoint to the JavaScript function: if it doesn't hit, something's wrong with your JavaScript.
Check your browser's network activity: In Chrome, under Developer Tools, go to the Network tab and attempt the upload. See if it is hitting the right URL.
Make sure you're using '#Url.Action...' inside a Razor view. It won't work in external JavaScript files.
If you need #Url.Action, you can probably use it in your Razor view, assign it to a temporary global variable and use it in your external JavaScript file.
In your View, add the following before the reference to your external JS:
<script type="text/javascript">
var audioAction = '#Url.Action("Upload", "Audio")';
</script>
In your JavaScript file, change '#Url.Action("Upload", "Audio")' to audioAction, as in:
function AudioUpload(title, description) {
Recorder.upload({
method: "POST",
url: audioAction,
audioParam: "Recording",
params: {
"Title": title,
"Description": description
},
success: function (responseText) {
alert(responseText.Success);
},
error: function () {
alert("error");
},
progress: NULL
});
}

Related

Backbone Paginator click event

I am new to backbone and am using backbone in my rails application . This is what I am doing in my application
I am using Backbone Paginator for pagination support in my application as well using Gmaps for rendering locations on gmaps , for each time I am displaying 5 records from the server with pagination and displaying corresponding 5 location in map view , so now I need to show the remaining locations on map when I click on paginated links (prev page , next page) , I think I need to write some click events , but I am not sure where to write and how to write this events , Can any one please help me . please review the code below I have written evnets but those are not working
Thanks in advance
var Listings = Backbone.PageableCollection.extend({
model: Bdemo.Models.Listing,
mode: "server" ,
url: '/listings' ,
events: {
"click #paginationSelect" : "fetchSelectedData"
},
fetchSelectedData: function(){
console.log("CAMEEEEEEEEEEEEEEEEEEEEEEEEEEE")
},
// Initial pagination states
state: {
pageSize: 3,
/* sortKey: "updated",*/
order: 1
},
queryParams: {
totalPages: null,
totalRecords: null,
sortKey: "sort"
},
parseState: function (resp, queryParams, state, options) {
return {totalRecords: resp.total_pages};
},
parseRecords: function (resp, options) {
return resp.listings;
}
});
#ratnakar:
All you need is events function. Set an id for each of your paginated links. Then include the events function. I hope that you're developing SPA(single page application). With that note assume the following settings.
In the homeview.js("templates" folder) page include the paginated links enclosed by the footer tag.
<footer>
<button id="prevPage">previous</button>
<button id="nextPage">next</button>
</footer>
then the go to the corresponding homeview.js view file("views" folder)
backboneApp.Views.homeview = Backbone.View.extend({
//Default "events" function for handling delegate events.
events:{
//catching click events
"click #prevPage" : "goPrevious" //on click of DOM which has id as prevPage, calling a function goPrevious.
"click #nextPage" : "goNext" //same as above call goPrevious function.
},
//Defining the user created function goPrevious and goNext.
goPrevious: function(){
//Make your server call here.... for the previous 5 records.
},
goNext: function(){
// server call here for the next 5 records.
}
});
Thus the basic idea of using delegate events for paginated links is defined above.
From your question I understand that you are using backgrid-paginator in server mode.
Binding to the click event won't work, because you need to make sure that the models have been fetched from the server before you can access their data.
You can bind to your collections' request event and act on the xhr.done()
In your view:
initialize: function() {
this.listenTo(this.record_collection, "request", this.onCollectionRequested);
},
onCollectionRequested: function(collection, xhr, options) {
_this = this;
xhr.done(function(){
_this.showRecordLocationsOnMap(collection);
})
},
showRecordLocationsOnMap: function(records) {
/* Update your map here */
}
Hi finally solved this by calling my own function(callGmap) from Backbone.PageableCollection , here is my new code
var Listings = Backbone.PageableCollection.extend({
model: Bdemo.Models.Listing,
mode: "server" ,
url: '/listings' ,
events: {
"click #paginationSelect" : "fetchSelectedData"
},
fetchSelectedData: function(){
console.log("CAMEEEEEEEEEEEEEEEEEEEEEEEEEEE")
},
// Initial pagination states
state: {
pageSize: 3,
/* sortKey: "updated",*/
order: 1
},
queryParams: {
totalPages: null,
totalRecords: null,
sortKey: "sort"
},
parseState: function (resp, queryParams, state, options) {
return {totalRecords: resp.total_pages};
},
parseRecords: function (resp, options) {
callGmap(resp.hash);
return resp.listings;
}
});

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.

Why won't this JqueryUI autocomplete hit its URL?

I'm wiring the following method to my document.ready function. However, the "myAutoCompleteURL.aspx" URL is never being accessed (I have a breakpoint on the page, and it's never being hit).
Anybody know why this isn't working? I'm new to the UI version of AutoComplete; I had previously only used the jquery-based (deprecated) version.
function myAutoComplete(myTextBox, myLabel, myHidden) {
var myType = $(myLabel).html();
$(myTextBox).autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: "../myAutoCompleteURL.aspx",
data: { q: request.term, type: myType },
success: function (myData) {
response($.map(myData, function (myItem) {
return { label: myItem.name, value: myItem.name, id: myItem.id }
}));
}
});
},
select: function (event, ui) {
$(myTextBox).val(ui.myItem.name);
$(myHidden).val(ui.myItem.id);
return false;
}
});
}
You can remove the ../ in your url. I used to have the same issue sometime ago.
Secondly have an error function in your ajax call. If it hits the error function, then there is some problem in your data and you need to correct that.
As #GregL mentioned in his comment, that you are using JSON and not application/json :)
Use Firebug and look for what URL is being hit instead. If nothing shows up in the console, then the javascript code is not working at all.

Url pathname issue in Ajax Post

In development I make an Ajax post which works in development. However when I put it on the Test server it doesn't work because IIS has assigned the application a subfolder, and this is missing in my development environment.
I have found work around (see below) but I am the first to admit this should not be the solution, as I have to remember to call a function for the url everytime I make an Ajax call.
There must be a better way.
However the code will show you what I am fixing;
function OperationsManagerFlagClickFunc(userId) {
$.ajax({
url: GetUrl("/Users/UpdateOperationsManagerFlag"),
type: "POST",
data: { "userId": userId },
success: function (data) { }
});
}
function GetUrl(path) {
var pathArray = window.location.pathname.split('/');
if (pathArray[1] === "ITOC")
return "/ITOC" + path;
else
return path;
}
If you have your javascript in .aspx file, you can generate url like this:
function OperationsManagerFlagClickFunc(userId) {
$.ajax({
url: "<%= Url.Action("UpdateOperationsManagerFlag","User") %>",
type: "POST",
data: { "userId": userId },
success: function (data) { }
});
}
Why not have a variable defined separately, like siteUrl, that will hold your site's url, with different values on the 2 servers?
Then just do:
url: siteUrl + "/Users/UpdateOperationsManagerFlag"

Submit array param with jQuery ajax/load

public ActionResult DoSomething(string[] arr, bool someBool, int someInt) { }
trying to call the above method from jQuery:
var test = [];
test.push('dog');
test.push('cat');
$container.load('MyController/DoSomething',
{ 'arr[]': test, 'someBool': true, 'someInt': 1 },
function(response, status, xhr) {
// ...
});
the array paramater is null, other params are fine. What am I doing wrong?
Chrome developer tools shows form data being submitted as
arr%5B%5D%5B%5D:dog
arr%5B%5D%5B%5D:cat
someBool:true
someInt:1
not sure whats going on there but doesn't look right to me
If you are using jquery 1.4 you might need to set the traditional parameter to true in order to be compatible with the default model binder format in ASP.NET MVC:
var test = [];
test.push('dog');
test.push('cat');
$.ajax({
url: 'MyController/DoSomething',
type: 'GET',
traditional: true,
data: { arr: test, someBool: true, someInt: 1 },
success: function(result) {
$container.html(result);
}
});
or if you prefer the .load() method:
var data = { arr: test, someBool: true, someInt: 1 };
$container.load('MyController/DoSomething', $.param(data, true),
function(response, status, xhr) {
// ...
});
Just remove []
{ 'arr': test, 'someBool': true, 'someInt': 1 },
Posted values (checking with Firebug).
arr[] dog
arr[] cat
someBool true
someInt 1
Example on jsFiddle
can you see if this problem is similar to yours:
Passing an nested arrays to asp.net mvc using jQuery's $.ajax
Even i was facing error, in passing array from HTML page to aspx page.
my requirement was to load the aspx page in a DIV tag of the html page. on the page load i need to pass these JS array values to aspx page load.
i used below method.
$('#<divTagID>').load("Targetpage.aspx",{"Arr":JSArrValues});
In aspx page load event i can access this values as:
string results = Response["Arr[]"];
Thanks to JQuery API documentation enter link description here and stackoverflow

Resources