I am working on ASP.net 2.0 web application using C#.
I need to upload a file where path of the file is in string.
Methos in cs file
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SendContactUsEmail(string volume, ...., string strFileName, string message)
{
// Other parameter is removed in method and written ...
// Need to upload file where path of the file is in string strFileName
//rqContact.PakkagingfileName = $('#packagingFile').val(); = strFileName
}
Value is passed from script.js is as below:
if(reqType == '5')
{
rqContact.height = $('#height').val();
rqContact.PakkagingfileName = $('#packagingFile').val();
}
$.ajax({
type: 'POST',
url: $('#webServiceUrl').val() + "/SendContactUsEmail",
contentType:"multipart/form-data; charset=utf-8",
//contentType:"application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify(rqContact),
error: function(){
//alert("Error in Contact-us Ajax call");
} ,
success: function( response )
{
trckContactUsEvent()
if (form.find( '.actionurl' ).attr('name') == 'actionurlcontactus'){
Cufon.refresh('.cufon-text');
$('.resultContainer p').html(response);
$('.resultContainer').attr('data-status','success');
$('.result').show();
$('.result').modal({
opacity:70,
overlayCss: {backgroundColor:'#000000'},
containerId: 'simplemodal-container4',
containerCss: {height:'48px'}
});
}
}
});
Please advise how to upload the file.
Regards.
You can use Ajax Upload to upload your file. You have to generate a .ashx(general handler) for your upload. you can send the path of the file to the handler and save the file to the path in the handler. this Tutorial describes how to use Uploadify jquery plugin to upload files. I do not recommend you to use Uploadify but the tutorial can help you learn how to use General Handler.
Related
I have tried to download a file from a method of my Web API Controller (Asp.net MVC 6). So, my file is created in a api controller and I want download my file, already in excel format, with angularjs. But, I don't know how to do.
Here is my method in my api controller: (it works, I already use this methods and class in an another project Asp.net without angularj)
#region downloadFile
[Route("Download")]
public ActionResult Download()
{
string companyName = Context.Session.GetString("companyName") as string;
string fileDownloadName = Context.Session.GetString("fileDownloadName") as string;
string baseFolder = System.IO.Path.Combine("C:\\Temp");
string folder = System.IO.Path.Combine(baseFolder, companyName);
TempFile tempFile = new TempFile(folder, fileDownloadName);
tempFile.FindFileInDirectory();
return File(tempFile._pathDirectory + "\\"+tempFile._fileName, "Application/" + tempFile._fileExt, tempFile._fileName);
}
#endregion
This method returns an excel file. Now, I would download this file that is send in angularjs with a http request.
I have tried to use the method saveAs from fileSaver.js. I have added the js in my project but when I want use it, the method is always undefined.
var requestDownloadFile =
$http({
url: '/api/customers/Download'
, responseType: 'arraybuffer'
, headers: {
'contentType': 'application/json'
, 'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
});
requestDownloadFile.success(function (data) {
saveAs(data, 'test.xlsx');
});
I tried to use this too in my success method:
var blob = new Blob([data], { type: "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet" })
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
It run a download file, but the file is corrupted.
So it's not realy effective because I have created a file in API and I have tried to recover an arrayBuffer but I'm blocked so I try.
All support is welcome. Thanks
So, I complicated life. I just had to do this in the success:
window.open('/api/customers/Download', '_blank', '');
window.open('link/to/method/api', '_blank', '');
I have a very simple page and a [WebMethod] inside it which returns a simple message. I would like to show this message through $.ajax on client side. however my website is using rewrites rules so my url becomes readable to user.
EX:
Actual webpage: www.mysite.com/about // which has about folder and a user control inside it
there is no aspx page for this instead i am using a method which gets a webpage data which is actual html page and show the content on user control.
here is Jquery part.
$(document).ready(function () {
$('.info a').click(function () {
$.ajax({
type: 'POST',
url: '/about/showServer', //which url to put here
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("result.d");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
});
});
});
C#
[WebMethod] // this method is in the user control
public static string showServer()
{
return "Hello from server";
}
How to call this method from client using $.ajax
appreciate your time and help.
EDITS
I have this structure for my website
mysite.com/about
/about/defualt.aspx --> which loads the user controls
user controls resides in
mysite.com/ConLib/Custom/about.ascx/showServer
So i set it to like this
url: '/ConLib/Custom/about.ascx/showServer',
BUT i see error in chrome developer tool in XHR request "404 error" because when you type mysite.com/conlib/blah blah ..reqrites does not allows this and throws 404 error..
Your ajax success method should be this:
alert(result.d);
Instead of this:
success: function (result) {
alert("result.d");
}
and url should be:
url: "Default.ascx/showServer", // UserControlPage/MethodName
you need to decorate your web method
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
public static string showServer()
{
return "Hello from server";
}
If your WebMethod is inside a User Control, then it needs to be moved to the ASPX page. See this post:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
The url: param should be in the form of '/MyPage.aspx/showServer'
My task is to save image into the database dynamically,whenever the user browses the img and clicks save button
I am using asp.net mvc3,razor view and mysql is my database
I am trying to pass the browsed img file to the controller and there in the controller i am converting it into byte format
and save it into the db.But when i put a braekpoint it is showing null,indicating that the file is not pasing to the controller
Could anyone please help me out in this
Below is my View and Controller
$(document).ready(function () {
$("#photos").kendoUpload();
$("#save").click(function (event) {
alert("started");
url = 'Home/Details';
var b;
$.ajax({
type: "POST",
url: '/Home/Details',
data: { b: $('#photos').load(url) },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (str) {
alert("hai");
alert(str.st);
}
});
});
});
Controller:
public ActionResult Details(HttpPostedFileBase b)
{
try
{
b = Request.Files[1];
byte[] imageSize = new byte[b.ContentLength];
b.InputStream.Read(imageSize, 0, (int)b.ContentLength);
Image g = new Image();
g.Img = imageSize;
dbContext.Add(g);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
}
var str = new { st = "saved" };
return Json(str, JsonRequestBehavior.AllowGet);
}
}
Firstly I don't think you can submit file using Ajax since it is against JavaScript security model. You will need to use some other way for posting it ajax way. Here are some JQuery plugin for ajax file upload :
http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/
If you want to use normal form post then you would have to set form element's encrypt property to "multipart/formdata" else the server just send file name and not the file itself.
You cannot upload files via standard AJAX
The return value of .load() is NOT the content loaded - it returns the jquery object. So you're trying to post the jquery object, NOT image data.
I have an asp.net WebMethod that returns an XmlDocument object.
I can successfully call the method using jquery ajax, but can't seem to get the function to succeed (server side webmethod gets called with correct parameters but client side method fails with 'undefined parser error').
To reproduce, Asp.net C#:
[WebMethod]
public static XmlDocument test(string name)
{
XmlDocument result = new XmlDocument();
XmlElement root = result.CreateElement("Data");
result.AppendChild(root);
XmlElement element = result.CreateElement("AnElement");
element.SetAttribute("Name", name);
root.AppendChild(element);
return result;
}
JavaScript:
function CallForData(name) {
$.ajax({
type: "POST",
url: "AppName.aspx/test",
data: "{'name': " + name+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (response) { ParseXML(response); },
error: function (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
});
}
If dataType: "xml" is commented out (automatic) the success function is called but the data is a load of square brackets that seem to indicate an empty json structure.
I want an XML response that I can parse using jQuery.
I think I possibly need to add some format identification to the XML document but aren't sure. Can anyone point out the problem?
Fixed by adding
[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]
to the web method.
Credit to riteshtandon23 in
this thread
I am creating Menu in the master page using JQuery. i am passing the id of the link to jquery using $.ajax({});
Problem:
Getting failed: Showing error message in AjaxFailed(result) function.
Code:html[JQuery]
$.ajax({
type: "POST",
url: "Master.Master.cs/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}
c# Code:Codebehind
private static List<string> xx;
[WebMethod]
public static List<string> UserStatus()
{
return xx;
}
protected void Page_Load(object sender, EventArgs e)
{
xx = new List<string> {"#ll1", "#ll2" };
}
What the webmethod attribute does is to say that this method should respond to a certain url (a little bit like routing in asp.net mvc). As I don't use webforms I don't really know what logic it uses when it decides what url the method should respond to. But my guess is that the url should be something like "Master.cs/UserStatus" (not sure about the .cs extension). And that is of course a relative url, so you can try something like this: <%=ResolveUrl("~/Master.cs/UserStatus")%> (if the masterpage is in your root folder). Then your example should be something like this:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/Master.cs/UserStatus")%>',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
Update
The .cs extension is probably wrong. But I don't think you should have that in a master page anyway. You should probably have it in a web service or in a .ashx handler or something if you want to use ajax. But with you last comment it seems that you don't need to use ajax (and if you don't need that, you shouldn't). The problem in the code you wrote in the comment is probably that the id is wrong (remember that you need the client id in javascript).
But I would probably do it something like this:
<script type="text/javascript">
var statuses = [];
<%foreach(var status in UserStatus()) {%>
statuses.push(<%=status%>);
<%}%>
</script>
This will render this javascript in the browser:
<script type="text/javascript">
var statuses = [];
statuses.push("#ll1");
statuses.push("#ll2");
</script>
Then you will have your statuses in the statuses array.
Like Andre and Mattias mentioned, the .cs extension is not served, so you would have to use a .aspx extension to get to the WebMethod.
The problem I see in your example is that you are placing the method in the MasterPage (which would have a .master extension) which is also not served, so you can't call the web method from it.
A workaround you could use is to define it in a class that inherits from Page, and have all of your pages inherit from that class. Since its a public method, it will be public on all of your pages and therefore available. Basicly, a base page for your project's pages. In that case you would only need to use your current page's address to make the call. This is only usefull if it's something you will use on every page, like a menu.
A second workaround you can use is to define the WebMethod in a .asmx Webservice placed in the project. It would work like calling the WebMthod on a page, only you would have to use the .asmx Webservice's address instead of the page's to make the call.
If you've not done so you will need to add the [ScriptService] attribute to your webmethod as this
Indicates that a Web service can be
invoked from script
See ScriptServiceAttribute
I think that the problem is that you try to post to the .cs file. The extension .cs is not served by ISS due to security reasons. So even though your method lifes in the code behind file, you have to post to the .aspx file. ASP.NET will do the rest for your.
So try:
$.ajax({
type: "POST",
url: "/Master.Master.aspx/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}