Menu
  • HOME
  • TAGS

How to AJAX POST file contents together with other data to ASP.NET Web API

Tag: asp.net,ajax,asp.net-web-api,filereader

I want to create a form where the user adds some information (text in inputs, selects, etc.) and uploads a file. For example if I have a Product entity that looks like this

public class Product
{
    public string Name { get; set; }
    public byte[] ProductImage { get; set; }
}

I want to do a POST via AJAX to a Web API action that looks like this

public void Post(Product product)

I want the name string and the bytes to be sent together. I don't want to upload the file in advance.

What should I do on the client to send the data preferably as JSON. One thing that seems easy is make ProductImage a string and send base64 encoded data which is easy to read with the FileReader API but is this the correct way? It seems cleaner to have the data map to a byte array which it actually is.

Best How To :

We ended up base64 encoding the file and sending it as part of the JSON then parsing it on the server into a byte array. One should be careful when allowing upload of large files but for small files it seems to be fine.

How to calculate values of a drop down menu with PHP/ JS?

javascript,php,ajax

I am not sure by your question if you want to add it to the db on the selection... that would require a simple but different code. This will accomplish what you are asking. You do not need a form... just the selection boxes. If you notice I encased each...

How do ASP.NET Web APIs work once built with MSBUILD?

c#,asp.net,msbuild

The WebApi is a web project and on compiling it creates a dll. It is not a class library or a nuget package to consume and use it. I have practically implemented this in a real world application and below are my thoughts for your understanding. Your question is Once...

WooCommerce seems to only orderby date and not price

php,ajax,wordpress,woocommerce

Try this: $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'beast-balls', 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'asc' ); ...

Why are fields reset after ajax update with Primefaces

ajax,jsf-2,primefaces

Why are fields reset after ajax update with Primefaces This problem has 2 possible causes depending on the concrete functional requirement: It's because you didn't tell JSF to process the desired input values. Or, it's because you told JSF to also update the non-desired input values. The solution depends...

Loading external php file in a div with jquery ajax

javascript,php,jquery,ajax,mysqli

You have to add jquery js in your html code. you can use online jquery. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> ...

Using $.ajaxStop() to determine when page is finished loading in CasperJS

javascript,jquery,ajax,phantomjs,casperjs

I would do something like this in include.js: (function(){ window._allAjaxRequestsHaveStopped = false; var interval; $(document).ajaxStop(function() { if (interval) { clearInterval(interval); interval = null; } interval = setTimeout(function(){ window._allAjaxRequestsHaveStopped = true; }, 500); }); $(document).ajaxStart(function() { if (interval) { clearInterval(interval); interval = null; } }); })(); This sets a (hopefully unique)...

Show/hide tinymce with radio buttons

c#,asp.net,asp.net-mvc,tinymce

Your missing an @symbol for the id attribute: Modify your script as well like this: ***EDIT some thing seems off about the radio buttons only one should be checked and they should have the same name ** you can use the # to denote and ID in Jquery by the...

WCF service architecture query

asp.net,architecture,wcfserviceclient

As long as you are able to use the exact same contract for all the versions the web application does not need to know which version of the WCF service it is accessing. In the configuration of the web application, you specify the URL and the contract. However, besides the...

How to return value in Meteor.JS from HTTP.call “GET”

javascript,ajax,http,meteor,facebook-javascript-sdk

Don't pass a callback to get the HTTP to return. You're also able to pass off URL parameters quite easily: var result = HTTP.call("GET", "https://graph.facebook.com/me", { params: { access_token : Meteor.user().services.facebook.accessToken, fields : "likes.limit(5){events{picture,cover,place,name,attending_count}}" } }); console.log(result); ...

Access manager information from Active Directory

c#,asp.net,active-directory

try this: var loginName = @"loginNameOfInterestedUser"; var ldap = new DirectoryEntry("LDAP://domain.something.com"); var search = new DirectorySearcher(ldap) { Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + loginName + "))" }; var result = search.FindOne(); if (result == null) return; var fullQuery = result.Path; var user = new DirectoryEntry(fullQuery); DirectoryEntry manager; if (user.Properties.PropertyNames.OfType<string>().Contains("manager")) { var managerPath...

jquery - add header request to specific ajax request

javascript,jquery,ajax

This is what you are looking for I believe. $( document ).ajaxSend(function( event, jqxhr, settings ) { if ( settings.url == "someURL" ) { jqxhr.setRequestHeader(key,value); } }); ...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

c#,asp.net,sql-server,date,gridview-sorting

What happens if you change all of the filters to use 'LIKE': if (DropDownList1.SelectedValue.ToString().Equals("Start")) { FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text); } Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date. Update Or perhaps you could try this... if (DropDownList1.SelectedValue.ToString().Equals("Start"))...

Automatically calling server side class without

javascript,html,ajax

Trigger the click event like this: $('._repLikeMore').trigger('click'); ...

Is there a way to fire an event every time an ajax call in made in AngularJS?

javascript,ajax,angularjs,express

In Angular this can be solved with an interceptor. See Angular-loading-bar as example.

cross domain ajax form post — How is this allowed?

jquery,ajax

If the server has a response header of 'Access-Control-Allow-Origin': '*' or something similar, it will return a response. In short, this has nothing to do with jQuery, and has everything to do with the server. In the case above, * is a wildcard representing all origins. But it could also...

Getting a collection via Ajax to show in view

jquery,ruby-on-rails,ajax

Your partial (currently named: _followup.html.erb in your example) should just be the code to produce a single row, Rails will iterate over it for you, and you should name it after the model it represents, ie. # app/views/assessments/_assessment.html.erb <%= assessment.name %> Then in your app/views/assessments/followups.html.erb view you'd use that partial...

When is the cookie set by AJAX available in javascript?

javascript,ajax,cookies

Cookies are passed as HTTP headers, both in the request and in the response. When you do an ajax call and set a cookie, that cookie will only be available in the browser after a reload / redirect happens, and new headers are gotten from the server containing the newly...

How to send current page number in Ajax request

javascript,jquery,ajax,spring-mvc,datatables

DataTables already sends parameters start and length in the request that you can use to calculate page number, see Server-side processing. If you still need to have the URL structure with the page number, you can use the code below: "ajax": { "data": function(){ var info = $('#propertyTable').DataTable().page.info(); $('#propertyTable').DataTable().ajax.url( "${contextPath}/admin/getNextPageData/"+(info.page...

asp.net background in 3 pieces to be stationary

html,css,asp.net

I would use a separate div and use fixed positioning on it. Example <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Layout Example</title> <link rel="stylesheet" type="text/css" href="./Layout Example_files/style.css"> <style type="text/css"> .fixed-background{ background: url( "images/SoapBubbles.jpg" ) no-repeat fixed top center; position:fixed; z-index:-1; top:0; right:0; left:0; bottom:0; } </style> </head> <body> <div...

Parameters from f:param not submitted with AJAX request when form enctype is multipart/form-data

ajax,jsf,jsf-2,jsf-2.2,wildfly

This is a bug in Mojarra. I've just reported it as issue 3968. For now, one work around is to pass them as EL method arguments instead. <h:form enctype="multipart/form-data"> <h:commandButton value="Submit" action="#{bean.action(true)}"> <f:ajax execute="@this" render="@this"/> </h:commandButton> </h:form> public void action(boolean myparam) { // ... } ...

add BR between text in dynamically created control

c#,asp.net

You need to use InnerHtml property HtmlGenericControl li = new HtmlGenericControl("li"); li.ID = "liQuestions" + recordcount.ToString(); li.Attributes.Add("role", "Presentation"); ULRouting.Controls.Add(li); HtmlGenericControl anchor = new HtmlGenericControl("a"); li.Attributes.Add("myCustomIDAtribute", recordcount.ToString()); anchor.InnerHtml = "Test <br/> 12345"; li.Controls.Add(anchor); Or, like this: anchor.Controls.Add(new LiteralControl("Test")); //or new Literal("Test"); anchor.Controls.Add(new HtmlGenericControl("br"));...

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework

If you don't specify a database name then the connection will use the default database for the user, in this case it's integrated security so it's your Windows login. As you likely have full system admin on the server the default database will be master so you will find all...

check if file is image

c#,asp.net,asp.net-mvc

You can't do this: string.Contains(string array) Instead you have to rewrite that line of code to this: if (file == null || formats.Any(f => file.Contains(f))) And this can be shortened down to: if (file == null || formats.Any(file.Contains)) ...

How to use ajax response JSON data?

javascript,jquery,ajax,json

As data is array of objects, use data[0].title: $('#myModalLabel').text('Review:' + data[0].title); // ^^^ ...

Retrieve data from one table and insert into another table

sql,asp.net,sql-server

INSERT INTO tbl2 ( Name ,parentId ) SELECT DISTINCT manager ,0 FROM tbl1 WHERE manager NOT IN ( SELECT employee FROM tbl1 ) INSERT INTO tbl2 SELECT DISTINCT employee ,0 FROM tbl1 UPDATE tbl2 SET parentid = parent.id FROM tbl2 INNER JOIN tbl1 ON tbl2.Name = tbl1.employee INNER JOIN tbl2...

How to make a website work only with https [duplicate]

asp.net,ssl,https

Sure, assuming you are using IIS to host your site, open IIS Manager and select your web site and then binding on the right: make sure you only have a binding for https not for http. This way IIS will only send https traffic to that web site. Edit: What...

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

Third-party security providers like Google, Twitter etc. in ASP.Net

asp.net,authentication

No, you cannot enter any string. You will need to register with each provider to get the parameters that you need. See http://www.asp.net/web-api/overview/security/external-authentication-services for instructions on how to do this....

Server side session in asp.net

asp.net,web-services,session

You've got a quotes problem, fix it like this: <% Session["path"] = "'" + vr_ + "'"; %> EDIT 1: Javascript and ASP.NET are not the same, so you cannot access the variables, so you can't do it on the client side. You must send something to the server like...

deployment of a site asp.net and iis

c#,asp.net,iis

There are several domain providers like: godaddy, name etc you can use to buy a domain name. These providers also provide you steps to map the domain name to your website. Check out this link for example. This link explains domain name configuration in details.

Convert Double from String

asp.net,vb.net,visual-studio-2012,converter

The result isn't wrong, it only has lower precision than you expected. Floating point numbers have a limited precision by design, and you simply can't expect to get a result that is more precise than its limit. You can use a Decimal to get higher precision. In this case it...

Can I uniquely identify 2 check boxes so that I can add a different image to each?

html,css,asp.net,checkbox

Here is an example of what I meant: (Oh and, forgive the images please :) ) #field1,#field2{ display:none; } #field1 + label { padding:40px; padding-left:100px; background:url(http://www.clker.com/cliparts/M/F/B/9/z/O/nxt-checkbox-unchecked-md.png) no-repeat left center; background-size: 80px 80px; } #field1:checked + label { background:url(http://www.clker.com/cliparts/B/2/v/i/n/T/tick-check-box-md.png) no-repeat left center; background-size: 80px 80px; } #field2 + label { padding:40px;...

onSuccess and onFailure doesn't get fired

javascript,c#,asp.net,webmethod,pagemethods

You PageMethod is looking like this PageMethods.LoginUser(onSuccess, onFailure, email, pass); And when you call it, it looks like this PageMethods.LoginUser(email, pass); Your arguments should be in the same order as the method. PageMethods.LoginUser(email, pass, onSuccess, onFailure); ...

Modal won't close on ajax success

jquery,ajax

You're using the wrong method to hide the element. Change this: $('#modal-container').modal('hide'); To this: $('#modal-container').hide(); Or if you want to completely remove it from the page, change it to this: $('#modal-container').remove(); ...

How use jquery getJSON with a local variable

javascript,jquery,ajax,json,ace-editor

JSON is JavaScript Object Notation, so this: [] or {} is JSON. I guess you only need: getCompletions: function(editor, session, pos, prefix, callback) { if (prefix.length === 0) { callback(null, []); return; } callback(null, wordList.map(function(ea) { return {name: ea.word, value: ea.word, meta: "optional text"} })); } $.getJSON will call the...

file input type not being included in jquery FormData for AJAX send

javascript,php,jquery,ajax

Your needs use enctype='multipart/form-data'. <form id="business-form" enctype='multipart/form-data'> </form> ...

Jquery parsley validate not working

javascript,php,jquery,ajax,parsley.js

Make sure this line: $('#remarks').parsley( 'addConstraint', { minlength: 5 }); is called before you check isValid()....

Creating a viewmodel on an existing project

c#,asp.net,asp.net-mvc

You are using a namespace, your full type name is Project.ViewModel.ViewModel (namespace is Project.ViewModel and class name is ViewModel) so use this using instead: @model Project.ViewModel.ViewModel ...

Run AJAX function on form submit button after javascript confirm() cancel

javascript,jquery,ajax,wordpress,forms

Dont use one(it will fire ajax submit or button click only once) , use here var IsBusy to check user is not repeatedly pressing the form submit, Try below code, var isBusy = false; //first time, busy state is false $('#publish').on('click', function (e) { if(isBusy == true) return ; //if...

Gridview items not populating correctly

asp.net,vb.net

Try this vb code behind, then comment out my test Private Sub BindGrid() Dim dt_SQL_Results As New DataTable '' Commenting out to use test data as I have no access to your database 'Dim da As SqlClient.SqlDataAdapter 'Dim strSQL2 As String 'Dim Response As String = "" 'strSQL2 = "SELECT...

How to write .htaccess file for AJAX page

php,jquery,ajax,.htaccess

I think it's more related to apache than ajax. Anyway - your RewriteRule is ^findcontents/([A-Za-z0-9-]+)/?$ and you post to the url '/findcontents'. Did you try to post to '/findcontents/asdf' ? Another option is to add ^findcontents$ to your rules. If none of these works for you please provide some more...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

Making an alert() with PHP and ajax

javascript,php,jquery,ajax

You're trying to output javascript from the php, without outputting it in your ajax callback, won't work. The easiest way to do what you want, is to return the string with your php, and handle the outputting to your javascript. something like : if($QueueCount == 1){ Echo "You already have...

Disable 2 buttons after click of a button

javascript,php,jquery,html,ajax

You can achieve this by disabling the buttons before you make the AJAX request, and then enabling them again in the complete handler of the request. Try this: var onSubmit = function(e) { var txtbox = $('#txt').val(); var hiddenTxt = $('#hidden').val(); $('.botleftbtn, .botrightbtn').prop('disabled', true); // < disable the buttons $.ajax({...

Unable to upload file to Sharepoint @ Office 365 via REST

javascript,ajax,rest,sharepoint,office365

To me it just seems a bit light, visit this link https://msdn.microsoft.com/en-us/library/office/dn769086.aspx on technet, and compare your upload function to this: // Add the file to the file collection in the Shared Documents folder. function addFileToFolder(arrayBuffer) { // Get the file name from the file input control on the page....

How to transform $.post to $.ajax?

javascript,jquery,ajax,json,servlets

$.post("../admin-login", { dataName:JSON.stringify({ username:uname, password:pass, }) }, function(data,status){ console.log("Data:"+data); answer = data; } ); becomes function getResult(data) { // do something with data // you can result = data here return data; } $.ajax({ url: "../admin-login", type: 'post', contentType: "application/x-www-form-urlencoded", data: { dataName:JSON.stringify({ username:uname, password:pass, }) }, success: function (data,...

Difference between application and module pipelines in Nancy?

c#,asp.net,nancy

The module- and application pipelines are explained in detail in the wiki. It's basically hooks which are executed before and after route execution on a global (application pipelines) and per-module basis. Here's an example: If a route is resolved to a module called FooModule, the pipelines will be invoked as...

how to use geocoder class to retrieve latitude and longitude through ajax

javascript,ajax,google-maps

Because of it's scope, your codeAddress javascript function is not visible for outer caller myLoop, as it is enclosed within myFunction, therefore you get the codeAddress is not defined. Try to rewrite your code similar to this (I have not tested, so it might not work right away, but you...

Identifier starts immediately after numeric literal

jquery,ajax,razor

I think you have to include it with the ' mark Like this : var userID = '@User.Identity.GetUserId()';...