Prevent Ajax/Json to refresh page after succes - asp.net

First i have now tried every page in here but nothing help. So this looks like all the others bus it isn't
i simply wants a file uploader where the image's are saved first and pass the image's ID back to a hidden input field as a string so i can find images again when the form is submitted.
no matter what i do i can't prevent the page for refreshing, which make the input field disappear :(
here is my code
HTML
<label for="file-uploader" class="custom-file-upload">
<i class="fa fa-cloud-upload fa-5x"></i><br /> Custom Upload
</label>
<input style="display: none" id="file-uploader" name="file" multiple="" type="file" />
<div id="input-wrapper">
Here comes all input fields
</div>
AJAX/JSON
$("#file-uploader").change(function () {
var formData = new FormData();
var totalFiles = document.getElementById("file-uploader").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("file-uploader").files[i];
formData.append("file-uploader", file);
}
$.ajax({
type: "POST",
url: '#Url.Action("Fileuploader", "Admin")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data, e) {
$('#input-wrapper').append($('<input>').attr('type', 'hidden').attr('name', 'imagesId').attr('value', data.Id));
},
error: function(error) {
alert("error");
}
});
return false;
});
CONTROLLER
public JsonResult Fileuploader(int? pictureId)
{
db = new ApplicationDbContext();
var name = "";
if (pictureId != null)
{
var findImage = db.Imageses.Find(pictureId);
if (findImage == null) return Json(new { result = "Error" }, JsonRequestBehavior.AllowGet);
var filename = findImage.Url.Substring(10);
var path = Server.MapPath("~/Uploads/" + filename);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
db.Imageses.Remove(findImage);
db.SaveChanges();
}
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
name = Guid.NewGuid().ToString();
var fileformat = Path.GetExtension(file.FileName);
var filename = name + fileformat;
var path = Path.Combine(Server.MapPath("~/Uploads/"), filename);
file.SaveAs(path);
}
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var img = new Images()
{
Filename = file.FileName,
DateCreated = DateTime.Now,
Url = "~/Uploads/" + name
};
db.Imageses.Add(img);
db.SaveChanges();
}
}
return Json(new { result = "Sucess", Id=name }, JsonRequestBehavior.AllowGet);
}

Is your #file-uploader sitting inside a form with an action method on it?
I would try taking the action attribute off, then adding the attribute to the form element in the success function of your ajax call.

I just disabled "enable Browser Sync" and it is working.

Related

How should I encode a form value I send with XMLHttpRequest [duplicate]

I'd like to send some data using an XMLHttpRequest in JavaScript.
Say I have the following form in HTML:
<form name="inputform" action="somewhere" method="post">
<input type="hidden" value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input type="hidden" value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
How can I write the equivalent using an XMLHttpRequest in JavaScript?
The code below demonstrates on how to do this.
var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
In case you have/create an object you can turn it into params using the following code, i.e:
var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;
// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
Or if you can count on browser support you could use FormData:
var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
Use modern JavaScript!
I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.
const url = "http://example.com";
fetch(url, {
method : "POST",
body: new FormData(document.getElementById("inputform")),
// -- or --
// body : JSON.stringify({
// user : document.getElementById('user').value,
// ...
// })
}).then(
response => response.text() // .json(), etc.
// same as function(response) {return response.text();}
).then(
html => console.log(html)
);
In Node.js, you'll need to import fetch using:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
const json = await fetch(url, optionalOptions)
.then(response => response.json()) // .text(), etc.
.catch((e) => {});
More Info:
Mozilla Documentation
Can I Use (96% Nov 2020)
David Walsh Tutorial
Here is a complete solution with application-json:
// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">
// return stops normal action and runs login()
<button onclick="return login()">Submit</button>
<script>
function login() {
// Form fields, see IDs above
const params = {
email: document.querySelector('#loginEmail').value,
password: document.querySelector('#loginPassword').value
}
const http = new XMLHttpRequest()
http.open('POST', '/login')
http.setRequestHeader('Content-type', 'application/json')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
// Do whatever with response
alert(http.responseText)
}
}
</script>
Ensure that your Backend API can parse JSON.
For example, in Express JS:
import bodyParser from 'body-parser'
app.use(bodyParser.json())
Minimal use of FormData to submit an AJAX request
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert (xhr.responseText); } // success case
xhr.onerror = function(){ alert (xhr.responseText); } // failure case
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData (oFormElement));
return false;
}
</script>
</head>
<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
<input type="hidden" value="person" name="user" />
<input type="hidden" value="password" name="pwd" />
<input type="hidden" value="place" name="organization" />
<input type="hidden" value="key" name="requiredkey" />
<input type="submit" value="post request"/>
</form>
</body>
</html>
Remarks
This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.
This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.
Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.
NO PLUGINS NEEDED!
Select the below code and drag that into in BOOKMARK BAR (if you don't see it, enable from Browser Settings), then EDIT that link :
javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); }; xhr.open(xForm.method, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);
That's all! Now you can visit any website, and click that button in BOOKMARK BAR!
NOTE:
The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script. That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that:
javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) { var xForm= document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank"); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } document.body.appendChild(xForm); xForm.submit(); } parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0);
I have faced similar problem, using the same post and and this link I have resolved my issue.
var http = new XMLHttpRequest();
var url = "MY_URL.Com/login.aspx";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
// Send the proper header information along with the request
//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
//http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
// Call a function when the state
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
This link has completed information.
Try to use json object instead of formdata. below is the code working for me. formdata doesnot work for me either, hence I came up with this solution.
var jdata = new Object();
jdata.level = levelVal; // level is key and levelVal is value
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://MyURL", true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(jdata));
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate
http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');
I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (i.e. PHP won't show any $_POST variables). You must pass the form header in to get that, and do that before http.send()
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
If you're using JSON and not URL-encoded data, pass application/json instead
var util = {
getAttribute: function (dom, attr) {
if (dom.getAttribute !== undefined) {
return dom.getAttribute(attr);
} else if (dom[attr] !== undefined) {
return dom[attr];
} else {
return null;
}
},
addEvent: function (obj, evtName, func) {
//Primero revisar attributos si existe o no.
if (obj.addEventListener) {
obj.addEventListener(evtName, func, false);
} else if (obj.attachEvent) {
obj.attachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = func;
} else {
obj[evtName] = func;
}
}
},
removeEvent: function (obj, evtName, func) {
if (obj.removeEventListener) {
obj.removeEventListener(evtName, func, false);
} else if (obj.detachEvent) {
obj.detachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = null;
} else {
obj[evtName] = null;
}
}
},
getAjaxObject: function () {
var xhttp = null;
//XDomainRequest
if ("XMLHttpRequest" in window) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhttp;
}
};
//START CODE HERE.
var xhr = util.getAjaxObject();
var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
if (isUpload) {
util.addEvent(xhr, "progress", xhrEvt.onProgress());
util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart);
util.addEvent(xhr, "abort", xhrEvt.onAbort);
}
util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState);
var xhrEvt = {
onProgress: function (e) {
if (e.lengthComputable) {
//Loaded bytes.
var cLoaded = e.loaded;
}
},
onLoadStart: function () {
},
onAbort: function () {
},
onReadyState: function () {
var state = xhr.readyState;
var httpStatus = xhr.status;
if (state === 4 && httpStatus === 200) {
//Completed success.
var data = xhr.responseText;
}
}
};
//CONTINUE YOUR CODE HERE.
xhr.open('POST', 'mypage.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if ('FormData' in window) {
var formData = new FormData();
formData.append("user", "aaaaa");
formData.append("pass", "bbbbb");
xhr.send(formData);
} else {
xhr.send("?user=aaaaa&pass=bbbbb");
}
This helped me as I wanted to use only xmlHttpRequest and post an object as form data:
function sendData(data) {
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for(name in data) {
FD.append(name, data[name]);
}
// Set up our request
XHR.open('POST', 'https://example.com/cors.php');
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
Short & modern
You can catch form input values using FormData and send them by fetch
fetch(form.action, {method:'post', body: new FormData(form)});
function send() {
let form = document.forms['inputform'];
fetch(form.action, {method:'post', body: new FormData(form)});
}
<form name="inputform" action="somewhere" method="post">
<input value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
<!-- I remove type="hidden" for some inputs above only for show them --><br>
Look: chrome console>network and click <button onclick="send()">send</button>
Just for feature readers finding this question. I found that the accepted answer works fine as long as you have a given path, but if you leave it blank it will fail in IE. Here is what I came up with:
function post(path, data, callback) {
"use strict";
var request = new XMLHttpRequest();
if (path === "") {
path = "/";
}
request.open('POST', path, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function (d) {
callback(d.currentTarget.response);
};
request.send(serialize(data));
}
You can you it like so:
post("", {orem: ipsum, name: binny}, function (response) {
console.log(respone);
})

how to disable a linkButton in aspx when a certain condition is set

Let me explain my problem, I have a LinkButton:
<asp:LinkButton ID="ForceUpdate" runat="server" OnClick="ForceUpdateBtn_Click" Text="<%$ Resources:Resource1, ForceUpdate%>" />
when I click on this LinkButton I set a command and then I check with JQuery if the button is clicked to show a message to wait until the machine is online to get the updated data and then disable the button:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);
Here's the method from the webservice where I check if in the db a certain data is set (CMD_Date_hour_Ok
!= null) to update the message that the machine is online and enable back the button.
[WebMethod]
public string GetUpdateStatusStats(string mccid, string language)
{
String strResponse = String.Empty;
CultureInfo currentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentCulture;
try
{
MCC_Machine mcc = MCC_Machine.Retrieve(Convert.ToInt32(mccid));
CMD_Command cmd = CMD_Command.RetrieveByMCCType(mcc, 14); // 14 means that a ForceUpdate were launched
if (cmd == null)
{
cmd = CMD_Command.RetrieveByMCCType(mcc, 14);
}
if (cmd.CMD_Date_hour_Ok != null)
{
// machine is online
strResponse = Resources.Resource1.ForceUpdateStatsOnline.ToString();
}
else
{
// machine is offline
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
}
catch
{
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
return strResponse;
}
Now I need to disable the LinkButton and maybe change the color to grey to get the idea that it is disabled when I click it and enable it when the machine is online.
How can I do that?
Thank you
You need to change disabled attribute of ForceUpdate at every interval as following:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
if(string =="Online"){ //check is machine online then set disable false
$("#<%=ForceUpdate.ClientID %>").attr("disabled", false);
}else{ // else mean machine is offline
$("#<%=ForceUpdate.ClientID %>").attr("disabled", true);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);

data table (View) not refreshing after jQuery Ajax call in mvc

I'm facing below issue while refreshing data that has been POSTed using Ajax in MVC. The POST is successfully being executed, but the data on the VIEW does not get refreshed with the new data. When I debug, the values from the Ajax POST are successfully being passed to my controller. When the controller returns the view model return View(objLMT);, my VIEW is not refreshing the new data. How do I get the new data to show in my VIEW?
AJAX
function getAllUserRoleCompany() {
debugger
var url = '#Url.Action("GetAllUserRoleCompany", "UserRoleCompany")';
var Organisation = $("#Organisation").val();
if (Organisation == "All") {
Organisation = "";
}
else {
Organisation = Organisation;
}
var RoleName = $("#RoleName").val();
if (RoleName == "All") {
RoleName = "";
}
else {
RoleName = RoleName;
}
var i = 0;
if ($("#UserName").find("option:selected").length >= 0) {
var len = $("#UserName").find("option:selected").length;
}
else {
len = 0;
}
var UserName = "";
for (; i < len; i++) {
if ($("#UserName").find("option:selected")[i].text != "All") {
if (i == 0) {
UserName = "',";
}
if (i < len - 1) {
UserName += $("#UserName").find("option:selected")[i].text + ",";
UserName = UserName.substring(0, UserName.indexOf("-")) + ",";
}
else {
UserName += $("#UserName").find("option:selected")[i].text + ",'";
UserName = UserName.substring(0, UserName.indexOf("-")) + ",'";
}
}
}
if (UserName == "All") {
UserName = ""
}
else {
UserName = UserName;
}
var UserStatus = $("#UserStatus").val();
if (UserStatus == "All") {
UserStatus = "";
}
else {
UserStatus = UserStatus;
}
$.ajax({
url: url,
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName, UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
//$("#dataTables-example").bind("");
//$("#dataTables-example").bind();
//location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Below is the view code on the same page
<div class="row">
#Html.Partial("pv_UserRoleCompany", Model)
Controller
public ActionResult GetAllUserRoleCompany(String Organisation, String RoleName, String UserName, int UserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string usrNameWithDomain = System.Web.HttpContext.Current.User.Identity.Name;
//string userID = "261213"; // Environment.UserName;
string userID = "100728";
ViewBag.UserRoleId = objLMTDAL.GetRoleID(userID);
objLMT.TypeList = objLMTDAL.UserRoleCompany_GetAll(Organisation, RoleName, userID, ViewBag.UserRoleId, UserName, UserStatus);
// return Json(objLMT, JsonRequestBehavior.AllowGet);
return PartialView("pv_UserRoleCompany", objLMT);
}
With above code My while SEARCHING or UPDATING view my table/Grid is not refreshing.
Kindly help.
If you are returning a partial view from an AJAX call you have to use jQuery to "refresh" the data.
In your js code you can do this:
$.ajax({
url: url,
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName,
UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
//$("#dataTables-example").bind("");
//$("#dataTables-example").bind();
//location.reload(true);
$("#dataTables-example").html(data);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
This will replace the existing HTML with the one from the partial view result in your controller.
#Mihail I have tried using the above solution. It Works I mean it refreshes my view but It's not loading my view perfectly as expected.
View Before (Expected)
View After using $("#dataTables-example").html(data);
Try if this works for you
Call this function as per your call:
function getAllUserRoleCompany(parameters) {
var token = $('[name=__RequestVerificationToken]').val();
$.ajax({
type: "POST",
url: '/UserRoleCompany/GetAllUserRoleCompany',
data: { Organisation: Organisation, RoleName: RoleName, UserName: UserName, UserStatus: UserStatus },
dataType: 'html',
success: function (data) {
$("#").empty().html(data);
}
});
}

How to send image into a specific folder?

I have an input element that selects an image as follows:
HTML Code
<input type="file" id="uploadEditorImage" />
Javascript Code
$("#uploadEditorImage").change(function () {
var data = new FormData();
var files = $("#uploadEditorImage").get(0).files;
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
type:"POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
},
error: function (er) {
alert(er);
}
});
And Code in MVC controller
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
}
I want to save the selected image in a specific folder such as C\Temp. How can I go about doing that? Please help.
Thank you.
in your html:
<input type="file" id="FileUpload1" />
script:
$(document).ready(function () {
$('#FileUpload1').change(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var data = new FormData();
var files = $("#FileUpload1").get(0).files;
console.log(files);
if (files.length > 0) {
data.append("HelpSectionImages", files[0]);
}
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: data,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
and backend:
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Content/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

How to do a ASP.NET MVC Ajax form post with multipart/form-data?

I am working on a ASP.NET MVC web site which has a form that allows for the upload of files using the multipart/form data enctype option on the form tag like so
<form enctype="multipart/form-data" method="post" action='<%= Url.Action("Post","Entries",new {id=ViewData.Model.MemberDetermination.DeterminationMemberID}) %>'>
How would I write this to do an ASP.NET MVC Ajax form post instead?
It is possible but it's a long way.
Step 1: write your form
ex:
#using (Ajax.BeginForm(YourMethod, YourController, new { id= Model.Id }, new AjaxOptions {//needed options }, new { enctype = "multipart/form-data" }))
{
<input type="file" id="image" name="image" />
<input type="submit" value="Modify" />
}
Step 2: intercept the request and send it to the server
<script type="text/javascript">
$(function() {
$("#form0").submit(function(event) {
var dataString;
event.preventDefault();
var action = $("#form0").attr("action");
if ($("#form0").attr("enctype") == "multipart/form-data") {
//this only works in some browsers.
//purpose? to submit files over ajax. because screw iframes.
//also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
dataString = new FormData($("#form0").get(0));
contentType = false;
processData = false;
} else {
// regular form, do your own thing if you need it
}
$.ajax({
type: "POST",
url: action,
data: dataString,
dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
contentType: contentType,
processData: processData,
success: function(data) {
//BTW, data is one of the worst names you can make for a variable
//handleSuccessFunctionHERE(data);
},
error: function(jqXHR, textStatus, errorThrown) {
//do your own thing
alert("fail");
}
});
}); //end .submit()
});
</script>
Step 3: Because you make an ajax call you probably want to replace some image or something of multipart/form-data
ex:
handleSuccessFunctionHERE(data)
{
$.ajax({
type: "GET",
url: "/Profile/GetImageModified",
data: {},
dataType: "text",
success: function (MSG) {
$("#imageUploaded").attr("src", "data:image/gif;base64,"+msg);
},
error: function (msg) {
alert(msg);
}
});
}
The MSG variable is an base64 encrypted string. In my case it's the source of the image.
In this way I managed to change a profile picture and after that the picture is immediately updated.
Also make sure you add in Application_Start (global.asax)
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
Pretty nice no?
P.S.: This Solution works so don't hesitate to ask more details.
I came across this little hack, which resolves it nicely
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
You can use some additional uploaders (e.g. jQuery multiple file uploader) (I prefer this way and I prefer not to use MS Ajax)
Use:
AjaxHelper.BeginForm("Post", "Entries", new {id=ViewData.Model.MemberDetermination.DeterminationMemberID}, new AjaxOptions(){/*some options*/}, new {enctype="multipart/form-data"})
But in second case I'm not sure that it will work.
The jquery forms plugin supports file uploads in this way.
Code which I used and it works !! It's a copy of #James 'Fluffy' Burton solution. I just improvising his answer so that people who is new to MVC will be able to quickly understand the consequences.
Following are my View:
#using (Ajax.BeginForm("FileUploader", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "AjaxUpdatePanel" }, new { enctype = "multipart/form-data", id = "frmUploader" })){
<div id="AjaxUpdatePanel">
<div class="form-group">
<input type="file" id="dataFile" name="upload" />
</div>
<div class="form-group">
<input type="submit" value="Upload" class="btn btn-default" id="btnUpload"/>
</div>
</div>}
<script>
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
Following are my controller:
[HttpPost]
public JsonResult FileUploader(HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
if (upload.FileName.EndsWith(".csv"))
{
Stream stream = upload.InputStream;
DataTable csvTable = new DataTable();
using (CsvReader csvReader = new CsvReader(new StreamReader(stream), true))
{
csvTable.Load(csvReader);
}
}
else
{
return Json(new { dataerror = true, errormsg = "This file format is not supported" });
}
}
else
{
return Json(new { dataerror = true, errormsg = "Please Upload Your file" });
}
}
return Json(new { result = true });
}
Following is the quick Note of above code:
Through Ajax, I have posted my excel (*.csv) file to Server and read it to an DataTable using a Nuget package (LumenWorksCsvReader).
Hurray! It works. Thanks #James
I actually answered the question myself...
<% using (Ajax.BeginForm("Post", "Entries", new { id = ViewData.Model.MemberDetermination.DeterminationMemberID }, new AjaxOptions { UpdateTargetId = "dc_goal_placeholder" }, new { enctype = "multipart/form-data" }))
For those who still have problems using #Ajax.BeginForm for multipart enctypes / file uploads in MVC
Diagnosis and proposed solution
Running the “Inspect element” tool on a form element generated by the #Ajax.BeginForm helper reveals that the helper, rather inexplicably, overrides the controller parameter specified. This is the case if you implemented a separate controller for your partial postback.
A quick-fix for the problem is to explicitly specify your html action attribute value as /<yourcontrollername>/<youractionname>.
Example
#using (Ajax.BeginForm("", "", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "<TargetElementId>", InsertionMode = InsertionMode.Replace }, new { enctype = "multipart/form-data", action = "/<Controller>/<Action>" }))
If you need to use the OnSuccess AjaxOption and/or use Request.IsAjaxRequest() in the controller to check the request type i.e.
#using (Ajax.BeginForm("FileUploader", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "elementToUpdate", OnSuccess = "mySuccessFuntion(returnedData)", OnFailure = "myFailureFuntion(returnedData)"}, new { enctype = "multipart/form-data" }))
Then you can use the following code (I've modified #James 'Fluffy' Burton's answer). This will also convert the response text to JSON object if it can (you can omit this if you want).
<script>
if(typeof window.FormData === 'undefined') {
alert("This browser doesn't support HTML5 file uploads!");
}
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.setRequestHeader("x-Requested-With", "XMLHttpRequest"); // this allows 'Request.IsAjaxRequest()' to work in the controller code
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var returnedData; //this variable needs to be named the same as the parameter in the function call specified for the AjaxOptions.OnSuccess
try {
returnedData = JSON.parse(xhr.responseText); //I also want my returned data to be parsed if it is a JSON object
}catch(e){
returnedData = xhr.responseText;
}
if (form.dataset.ajaxSuccess) {
eval(form.dataset.ajaxSuccess); //converts function text to real function and executes (not very safe though)
}
else if (form.dataset.ajaxFailure) {
eval(form.dataset.ajaxFailure);
}
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = data;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
</script>
N.B. I use the javascript function eval() to convert the string in to a function... if anyone has a better solution please comment.
I also use JQuery JSON.parse() so this isn't a vanilla javascript solution but it isn't required for the script to function so it could be removed.
I mixed Brad Larson answer with Amirhossein Mehrvarzi, because Brad answer wasn't providing any way to handle the response and Amirhossein was causing 2 postbacks.
I just added ($('#formBacklink').valid()) to call model validation before send.
window.addEventListener("submit", function (e) {
if ($('#formBacklink').valid()) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var dataString;
event.preventDefault();
var action = $("#formBacklink").attr("action");
if ($("#formBacklink").attr("enctype") == "multipart/form-data") {
//this only works in some browsers.
//purpose? to submit files over ajax. because screw iframes.
//also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
dataString = new FormData($("#formBacklink").get(0));
contentType = false;
processData = false;
} else {
// regular form, do your own thing if you need it
}
$.ajax({
type: "POST",
url: action,
data: dataString,
dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
contentType: contentType,
processData: processData,
success: function (data) {
//BTW, data is one of the worst names you can make for a variable
//handleSuccessFunctionHERE(data);
},
error: function (jqXHR, textStatus, errorThrown) {
//do your own thing
}
});
}
}
}
}, true);
Ajax.BegineForm() works with multipart form data and here's the working code example for the same:
View:
#using(Ajax.BeginForm("UploadFile","MyPOC",
new AjaxOptions {
HttpMethod = "POST"
},
new
{
enctype = "multipart/form-data"
}))
{
<input type="file" name="files" id="fileUploaderControl" />
<input type="submit" value="Upload" id="btnFileUpload" />
}
Controller Action Method:
public void UploadFile(IEnumerable<HttpPostedFileBase> files)
{
HttpPostedFileBase file = files.FirstOrDefault(); //Attach a debugger here and check whether you are getting your file on server side or null.
if (file != null && file.ContentLength > 0)
{
//Do other validations before saving the file
//Save File
file.SaveAs(path);
}
}
P.S. Make sure the "name" attribute of the file uploader control and the name of the parameter passed to Action method UploadFile() has to be same (i.e. "files" in this case).
From my little investigation. All the answers above seems to be correct depending on the problem one is having with the Ajax.BeginForm. However, I have just observe that the problem is with the ~/Scripts/jquery.unobtrusive-ajax.min.js javascript library in some case. So in my case I just removed it from the view model and sort of decided to use JQuery Form plugin for my required need along with the HTML Form instead. This has been suggested above.
You can use this code instead of eval
var body = "function(a){ " + form.dataset.ajaxSuccess + "(a) }";
var wrap = s => "{ return " + body + " };"
var func = new Function(wrap(body));
func.call(null).call(null, returnedData);

Resources