how to pass file from client to controller by jquery? - asp.net-mvc-4

i want to create very simple sample to uploading a file by client side in mvc4 by jquery and java script.
i Google it and found many samples and many plugins on internet but i prefer to do not have any dependency on any extra plugin or library like "uploadify"
for this i create a simple mvc4 application and in my view i attach my script file that contains method bellow until user click a button on this view start to uploading.
i do not know how to change bellow method to pass file to controller(in client side) ?
function uploadimage() {
$.ajax({
url: "/Uploader/FileUpload",
type: 'POST',
dataType: 'json',
data:null,
contentType: 'application/json; charset=utf-8',
success: function (msg) {
},
error: function (xhr) {
}
});
}
in my view
<input type="file" id="fileToUpload" name="file" />
<input type="button" value ="Upload" onclick="uploadimage()"/>
my controller
public ActionResult FileUpload(HttpPostedFileBase file)
{
//do somethings with file
}

file upload is not possible through ajax. You can upload file, without refreshing page by using IFrame.

Related

How to invoke a backend function in JS in a Smarty template used in a Prestashop module?

In a custom prestashop module, I am trying to dynamically show children categories in a dropdown.
This is the code I add in the hook before calling the template:
$subcatObj = new Category("24");
$subcatObj2 = $subcatObj->getSubCategories($this->context->language->id);
$this->context->smarty->assign('seriesCategories', $subcatObj2 );
This is how I use this in the template:
<select id="series_dropdown" class="selectpicker" data-style="btn-primary">
{foreach from=$seriesCategories item=seriesCategory}
<option value="{$seriesCategory.id_category}">{$seriesCategory.name}</option>
{/foreach}
</select>
What I need is to invoke this getSubCategories with different values from JS, to dynamically populate the dropdown. So instead a hardcoded 24, I would like to use a JS variable.
$subcatObj = new Category(******** JAVASCRIPT VARIABLE *********);
$subcatObj2 = $subcatObj->getSubCategories($this->context->language->id);
What shall be done to achive this? -It is sort kind of AJAX web service-
Prestashop 1.7.1
You need create a php file in your module to handle the ajax request, eg:
/modules/your_module/ajax.php
<?php
require_once(dirname(__FILE__).'/../../config/config.inc.php');
$subcatObj = new Category((int)Tools::getValue('id_category'));
$subcatObj2 = $subcatObj->getSubCategories((int)Context::getContext()->language->id);
die(Tools::jsonEncode($subcatObj2));
Now in JavaScript inside the .tpl, or by a .js file loaded there:
$.ajax({
url: '/modules/your_module/ajax.php',
type: 'POST',
dataType: 'JSON',
data: { id_category: $('#series_dropdown').val() }
})
.done(function(data) {
console.log(data); // 'data' should contain the response of corresponding sub-categories
})
.fail(function() {
console.log('An error has occurred!');
});
PD. This is a basic example, you should add some security token in the ajax.

Url.Action in asp.net core

I like the new tag helpers attributes which make readable dynamic html contents. I can create a link by using the asp-controller and asp-action attributes like this:
<a asp-controller="Home" asp-action="Index">Index</a>
The problem is that there are cases where I need just the URL of the action in order to use it my javascript. For example in order to make an ajax call in ASP.NET MVC 5, I could have the following code:
$.ajax({
type: "POST",
url: '#Url.Action("GetData","Ajax")',
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
I tried to find an equivalent method in ASP.NET Core but I was not able to find one so I have to create the URL myself. Is there a way to get the Action and Razor Page URL in ASP.NET Core.
I just found how to do it. In case someone else is looking for the same thing here is how to do it.
#this.Url.Action("Index", "Home")

Cloudinary jQuery Direct Upload issue

I am implementing Cloudinary Jquery Upload. From my file upload webpage, if I surf to another website ( google.com, or any external website), and then click on the back button on the browser into this same file upload page, the upload fails.
The error message I gotten back is (from Firebug):
400 Bad Request
{"error":{"message":"Upload preset Must specify upload preset when using unsigned upload”}}
I did not enable unsigned upload on the Cloudinary management console
because my intention is a signed upload
This is the JSON data that is created at the backend for data-form-data:
{"timestamp":1409146953,"callback":"http://newappsure.herokuapp.com/vendor/cloudinary/cloudinary_cors.html","signature":"19071a3e822eed51238454e359589f52cccca042","api_key":"224456847515364”}
Below is the javascript and input HTML:
<script type="text/javascript”>
$.cloudinary.config({cloud_name:'dashy', api_key:’XXXXXXXXXXXXXXX'});
</script>
<input name="file" type="file" id="uploadinput" class="cloudinary-fileupload" data-cloudinary-field="image_upload"
data-form-data="" ></input>
<script>
$.ajax({
url: '/filer',
type: 'POST',
success: function(response){
$('#uploadinput').attr('data-form-data', response);
}
});
</script>
This is the Ruby backend that generates JSON:
post '/filer' do
ts = Time.now.getutc.to_time.to_i.to_s
secret="XXXXXXXXXXXXXXXXXXXXXX"
altogether="callback=http://newappsure.herokuapp.com/vendor/cloudinary/cloudinary_cors.html&timestamp="+ts+secret
sig=Digest::SHA1.hexdigest altogether
ts = Time.now.getutc.to_time.to_i
{:timestamp => ts, :callback => "http://newappsure.herokuapp.com/vendor/cloudinary/cloudinary_cors.html", :signature => sig, :api_key =>"XXXXXXXXXXXXXXXX"}.to_json
end
Please help me understand what did I do wrong?
While your solution may work, the more optimal way is to update the upload parameters to call $(...).fileupload({formData: data}) where data is the parameters hash (not JSON serialized).
For more information:
http://support.cloudinary.com/entries/24950218-Why-is-updating-a-cloudinary-fileupload-field-dynamically-not-working-
Got it working by forcing the page to reload with the following snippets (ref: https://stackoverflow.com/a/9217531/3781343 and http://www.webdeveloper.com/forum/showthread.php?137518-How-to-refresh-page-after-clicking-quot-Back-quot-button)
<input type="hidden" id="refreshed" value="no">
<script type="text/javascript">
onload=function(){
var e=document.getElementById("refreshed");
if(e.value=="no")e.value="yes";
else{e.value="no";location.reload();}
}
</script>

MVC 4 Invoking Actions from buttons

Im new to MVC and I need to know How to invoke Action Methods from a view's buttons. And i need to clarify the difference between button and submit
Thanks
The buttons usually belong to a form tag. A form has a submit url. When the button <input type="submit" value="Submit"> is pressed you are redirected to the url written in form submit. Action Method is tied to a web page. For example if you go to www.eample.com/home/hello you execute Hello action in Home controller.
You can use jQuery to fire AJAX calls to specific pages (for example /home/process) and change the data on the page. To do that you should bind onclick javascript event on the button and there perform ajax call.
Example of AJAX call when page is loaded:
function loadContent() {
$.ajax({
type: 'get',
url: 'Page.html',
contentType: 'application/html; charset=utf-8',
dataType: 'html',
beforeSend: sendContent,
success: successContent,
error: errorContent
});
}
function sendContent() {
////loading
}
function successContent(data, status) {
$("#content .main").html(data);
$("#content").show();
}
function errorContent(request, status, error) {
////error
}
$(function () {
loadContent();
});

Multi language support in Hot towel(Durandal framework)

I'm in the process of creating a application using Hot Towel, which supports multiple language (eg. english, french)
I have the referred the following links
Translating Views
Durandal localization example
And my question is how can i render views of application based on user language. If user selects english, the complete application should display contents in english. How to achieve this
I have tried something like in the second link.
define({
'root': {
welcome: 'Welcome!',
flickr: 'Flickr'
},
'fr-fr': true,
'es-es': true,
});
Is this i have to create seperate views for languages or i have to create seperate App folder for contents
Suggest me some best practices.
I don't recommend using separate views or separate folders if your project is a big one.
You can just create a file of the labels and if you use lib like knockout just data-bind these labels once (text: xxxx). In addition you can use i18n to manage labels.
With selected language just load the specific language file to your viewmodel.
EDIT1:
I'd never encountered a complete sample nor tutorial. So how I do is to :
use tools like i18n to get the key-paired dictionary file for labels in html and in some javascript code like messages.
then manually I indexed these labels by augmenting knockout viewmodels for views and variables for modules.
This is my last option in waiting for better solution. Hope this can help!
you can do some thing like this . YOu can change the APP folder if you are need do lot of locale changes you can use the following method
#{
string strAcceptLanguage;
strAcceptLanguage = System.Configuration.ConfigurationManager.AppSettings["Locale"].ToString();
if (strAcceptLanguage == "en-us")
{
#Scripts.Render("~/Scripts/vendor.js")
<script type="text/javascript" src="~/Scripts/require.js" data-main="en-US/main"></script>
}
else if (strAcceptLanguage == "es-es")
{
#Scripts.Render("~/Scripts/vendor.js")
<script type="text/javascript" src="~/Scripts/require.js" data-main="en-UK/main"></script>
}
else if (strAcceptLanguage == "fr-fr")
{
#Scripts.Render("~/Scripts/vendor.js")
<script type="text/javascript" src="~/Scripts/require.js" data-main="AUZ/main"></script>
}
}
in the Index.cshtml you can use the above code and for the you need to have value in Webconfig file
<add key="Locale" value="en-us" />
and in the SPA page each time when the user try to change the locale by pressing button or any kind of option you have to trigger a event to call a AJAX post to assess a REST api to update the Given Locale Value in the webconfig file
changeLocale: function (val) {
var name = JSON.stringify({
locale: val
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/Locale",
type: "POST",
dataType: "json",
data: name,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert(json);
location.reload();
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
you have to write the above code in the shell.js and the shell.html has the following code
<div class="btn-group" data-toggle="buttons-radio">
<button type="button" class="btn btn-primary" data-bind="click: changeLocale.bind($data, 'en-us')">English</button>
<button type="button" class="btn btn-primary" data-bind="click: changeLocale.bind($data, 'es-es')">French</button>
<button type="button" class="btn btn-primary" data-bind="click: changeLocale.bind($data, 'fr-fr')">Japanese</button>
</div>
And the rest api like this
[HttpPost]
public string ChangeLocale(Locale l)
{
ConfigurationManager.AppSettings["Locale"] = l.locale;
return "success";
}
hope this will help