Uploading a file to an ASPX server-side page - c#

I'm having trouble understanding how to send an uploaded file's content to my ASPX server-side. This is for an HTML-4 implementation where File API isn't available on the client-side, and using .NET v4.0.
Here's what I have so far:
HTML on FileReceiver.aspx:
<input type="button" id="uploadFile" value="Upload" />
<div class="hidden">
<form id="uploadFileForm">
<input type="file" id="browseForFiles" />
</form>
</div>
(client-side) JS:
$("#uploadFile").click(function () {
$("#browseForFiles").click();
});
$("#browseForFiles").change(function () {
$("#uploadFileForm").submit();
});
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
// send file to server
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "post",
dataType: "multipart/form-data", // <---- is this right?
data: ???, // <-------------------------- what goes here?
success: function(data) {
// do something on success
}
});
});
(Server-side) FileReceiver.aspx.cs:
[WebMethod]
public static string ReceiveFile(??? receivedFile) // <-- what type goes here?
{
// do something and return status
}
Please help fill in the two "???" in the codes above. Thanks in advance!

This should work
$("#uploadFileForm").submit(function (e) {
// prevent default action
e.preventDefault();
var formData = new FormData($('#uploadFileForm')[0]);
$.ajax({
url: "FileReceiver.aspx/ReceiveFile",
type: "POST",
// Form data
data: formData, // <-- see above to see where this comes from
dataType: "json", // <-- the dataType you're RETURNING, not sending
cache: false,
//Options to tell jQuery not to process data or worry about content-type.
contentType: false,
processData: false,
success: function(data) {
// do something on success
}
});
});
Then your C# code should look like this
[WebMethod]
public static string ReceiveFile(HttpPostedFileBase receivedFile)
{
// do something and return status
}

Related

I am trying to send an uploaded file from the view to the controller using an ajax call but the file is received as null in the controller

I am sending an uploaded file from the html view to the controller using ajax but the file is received as null in the controller.
I tried using FormData but nothing happens or maybe I am not using it right, when I sent the file using html.BeginForm() it was read correctly in the controller but I don't want to use forms because it opens another page after submitting
Below is my controller
public void Upload_SCN_CA_File(FormCollection formCollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
Debug.WriteLine(fileName);
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
}
}
}
Below is the JQuery ajax call
$("#upload").on("click",function () {
$.ajax({
type: "POST",
url: "/Order/Upload_SCN_CA_File",
data: {
enctype: 'multipart/form-data'
},
success: function (response) {
if (response.result == false) {
swal("Error", response.message, "error");
}
else {
swal("Success", response.message, "success");
}
}
});
});
Below is my html view
<form>
<div class="row">
<div class="col">
<input name="UploadedFile" id="upfile" type="file" />
</div>
</div>
<div class="row">
<div class="col">
<div class="btn btn-primary rounded" id="upload" style="margin:8px">Upload</div><br>
</div>
</div>
</form>
I expect the file to be sent correctly to the controller so I can read it correctly but it is received as null
You may pass data something like in bellow code.
$("#form0").submit(function (event) {
var dataString;
event.preventDefault();
event.stopImmediatePropagation();
var action = $("#form0").attr("action");
if ($("#form0").attr("enctype") == "multipart/form-data") {
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",
contentType: contentType,
processData: processData,
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
You must pass the form's content in the request using FormData API. You can collect it for example like this in the click handler
const form = $(this).closest('form').get(0)
const data = new FormData(form)
Then pass the following to the ajax call
data: data,
processData: false,
contentType: false
instead of
data: {
enctype: 'multipart/form-data'
},
processData: false makes jquery pass the FormData instance unmodified to the XHR, which is required for the file upload to work. contentType: false will make the browser set multipart/form-data content type automatically.
FormData doest now work in older browsers, IE<10 specifically.

Accessing request from external url

Hi I'm new to umbraco MVC. I'm using version 7. What I'm trying to do is following:
An External page www.ble1.com is posting to my page www.le2.com/recieve when that happens ble1 is posting to the page and in the browser dev tools I can see the Form Data name of the parameter (tok) and some encoded string.
Now I want to take this data and send it to the controller code behind the macro running on my page www.le2.com/recieve. How would this be possible? I'm used to workin in asp.NET where I have the pageLoad function in code behind but I'm confused how to tackle this in Umbraco MVC.
What I have done so far is Create cshtml:
#inherits Umbraco.Web.Macros.PartialViewMacroPage
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '../../../umbraco/surface/land/Login',
data: JSON.stringify({}),
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data.d);
}
});
});
</script>
My Controller
public JsonResult Login()
{
//Don't know what to do here!!!!
//Everything that I have tryed has failed. Calling Request....etc.
}
I have never worked with Umbraco, but I have with MVC.
You Login method is not marked to receive POST requests. You need to use the attribute [HttpPost]
Your Login method does not have any Arguments, so, even if you fix your issue #1, it will not get any data.
So, first, you need some data in your Action Method, so you either need a ViewModel or a set or parameters, this is a ViewModel sample:
public class MyLoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
Now we use that ViewModel in the Action Method:
[HttpPost]
public JsonResult Login(MyLoginViewModel model)
{
if (ModelState.IsValid)
{
// Do something here (probably use Umbraco internal's authorization layer)
var valid = (model.UserName == "user" && model.Password == "pwd");
if (valid)
return Json(new { code = 0, message = "OK" });
else
return Json(new { code = 10, message = "User/Password does not match" });
}
// Model is invalid, report error
return Json(new { code = -1, message = "invalid arguments" });
}
It is a very naive example, it makes sure the ViewModel is Valid, if it is, it performs the actual login logic, in this sample is just checks 2 values and returns the status.
In the HTML page, you could have:
<input type="text" id="userName" />
<input type="text" id="password" />
<button id="login">Login</button>
<script>
$(document).ready(function () {
$("#login").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/home/Login',
data: JSON.stringify({ UserName: $('#userName').val(), Password: $('#password').val() }),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert("An error has occurred while processing your request");
}
});
})
});
</script>
Again, very a naive example.
I hope it gives you enough information to adapt it to Umbraco.
Sorry I cannot give you Umbraco specific information.

Change page in browser after end of controller

How can i change page in browser, after end of controller?
I tryed this:
Html/JS code:
<form>
<button type="submit" onclick="abc()">123</button>
</form>
<script>
function abc()
{
$.post("/", "abc", function () {
});
}
</script>
ASP.NET MVC Code:
[HttpPost]
public ActionResult Index(dynamic response)
{
return Redirect(Request.UrlReferrer.ToString() + "/Home/OtherPage");
}
What am I doing wrong?
[HttpPost]
public ActionResult Index(dynamic response)
{
return RedirectToAction("OtherPage", "Home");
}
Check this solution -
Your Action should be like this -
public ActionResult RedirectMe()
{
return new JsonResult() { Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Then your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
When you Click the button, you will be redirected to the Google. You have to make sure you construct a proper URL (instead of google) and send it back.
If you want to pass some parameters to Action, then follow this way -
public ActionResult RedirectMe(string id)
{
return new JsonResult(){ Data = "http://www.google.com", JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}
Finally your JQuery POST should be -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("RedirectMe")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: "This is my parameter"}),
success: function (data) {
window.location.href = data;
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
If you want to redirect to another page in your client code, You may send the new url in a JSON response and use window.location.href property to naviagate to that.
[HttpPost]
public ActionResult Index(dynamic response)
{
//Do your other work
string newUrl=Request.UrlReferrer.ToString() + "/Home/OtherPage";
//It may be better to use the Helper methods to get the url.
return Json(new { NewUrl=newUrl);
}
In your ajax call
$.post("YourURLHEre",{ response :YourDataHere},function(res){
window.location.href=res;
});

Ajax jQuery not always executes action on Controller

I have the Controller method below made in ASP.NET MVC 3 (C#) who returns a PartialView:
public ActionResult InsertEmail(long idPerson)
{
PersonEmailViewModel mail = new PersonEmailViewModel();
mail.email.Person_idPerson = idPerson;
return PartialView(mail);
}
The method that I need to execute on submit form is:
[HttpPost]
public ActionResult InsertNewEmail(PersonEmail mail)
{
mail.idPersonEmail = mail.Insert(mail);
return Json(mail);
}
My partialView contains this code:
#model PlatformLib_MySql.BLL.Person.PersonEmailViewModel
<form action="" id="frmNewEmail" method="post">
<div>
E-mail: #(Html.TextBoxFor(m => m.email.email))
#(Html.HiddenFor(m => m.email.Person_idPerson))
<input type="submit" value="Insert" id="btnSubmitMailInsert" />
<input type="button" value="Cancel" id="btnCancelMailInsert" />
</div>
</form>
In my JS file I run this code on #btnSubmitMailInsert button:
jQuery("#btnSubmitMailInsert").click(function () {
submitNewEmail();
window.location.reload();
});
function submitNewEmail() {
event.preventDefault();
var mail = {
email: jQuery("#frmNewEmail #email_email").val(),
Person_idPerson: jQuery("#frmNewEmail #email_Person_idPerson").val()
};
var request = jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
});
request.done(function (msg) {
console.log(msg);
});
request.fail(function (msg) {
console.log(msg);
});
}
My problem is focused on Ajax request. Rarely I can make the "happy way", where on submit click, the event is activated on jQuery, calls the method "submitNewEmail()", that calls an Ajax, executes the method on controller and pass with success. But not so... It always returns with fail, not because error returned by controller method, but simply because ajax doesn't runs properly, doesn't execute the method on controller, even with a breakpoint inserted there (on VS2010).
In this JS code posted by me here is an attempt to alternatively solve this problem, unsuccessful.
The original code is:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false,
success: function (result) {
debugger;
jQuery("#tblEmail").append("<tr><td>Email inserido</td></tr>");
},
error: function () {
debugger;
alert("Erro ao inserir e-mail.");
}
});
I left the "console.log(msg)" temporary, just to solve this problem.
Can someone of you tell me what is happening, or to point where is my error?
I found the problem. Everything was right, but some detail damaged the code: window.location.reload();
I made some changes in my code, that looks like it:
jQuery.ajax({
url: '/Person/InsertNewEmail',
data: mail,
type: 'POST',
dataType: 'json',
cache: false
}).done(function (data) {
// Do something
});
The another way is right too, the only relevant change was:
jQuery("#btnSubmitMailInsert").click(function () {
event.preventDefault();
submitNewEmail();
// window.location.reload // -> Commented for testing and everything worked fine.
});
Thanks for trying to help me. This helped me so much.

calling function in the javascript written in webpage(.cs)

I have function on .cs page
[System.Web.Services.WebMethod]
public static string getdata()
{
ProductBAL objbal = new ProductBAL(); // Calling class
int i = 0;
i = objbal.get_last_orderid(); //Select query
i = i + 1;
ProductDAL objdal = new ProductDAL(); // Calling class
objdal.insert_new_orderid(i); //Insert query
HttpCookie orderid = new HttpCookie("orderid");
orderid.Value = "MP_" + Convert.ToString(i);
Response.Cookies.Add(orderid);
Response.Cookies["orderid"].Expires = DateTime.Now.AddHours(5);
string abc=Convert.ToString(i);
return abc;
}
My Html page code is
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>calling function from .cs</title>
<script language="javascript" type="text/javascript">
function Submit1_onclick() {
$.ajax({ type: "GET", url: "default.aspx/getdata()", success: function (data) { });
alert("Done");
}
</script>
</head>
<body>
<form name="ecom" method="post" action="https://www.google.co.in/">
<input id="Submit1" type="submit" name="submit" runat="server" value="Submit" onclick="return Submit1_onclick()">
</form>
</body>
I am trying to call my web side function to client side on submit click.
Am I missing something? Please give a demo from my above code
function Submit1_onclick() {
// alert("Hello");
$.ajax({
type: "GET",
url: 'demo.aspx/getdata',
data: "{}",
//"{character:'M'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
//alert("success");
alert("This is ajax call:");
},
error: function() {
//alert(Error);
alert("something went wrong");
}
});
// alert("Done");
}
[WebMethod()] //U have to declare this method as a web method
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string getdata()
{
On your url try : "PageName.aspx/MethodName". Also check out this blog post by Dave Ward :
Using jQuery to directly call ASP.NET AJAX page methods
Below line is error prone. do not include "()" in url method name.
$.ajax({ type: "GET", url: "/getdata()", success: function (data) { });
Replace above line with
$.ajax({ type: "GET", url: "/getdata", success: function (data) { });
See the following working example
// Code behind method declared static
[WebMethod]
public static string GetSquare(String value)
{
return "hello" + value;
}
your button whose click this has to be done
<input type="button" id="button" value="Chnageurl" onclick="ajaxcall()" />
script for this
<script type="text/jscript">
function ajaxcall(e) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSquare",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ value: "test" }),
dataType: "json",
success: function (value) {
alert(value.d);
},
error: function () { alert("Ajax Error"); }
});
};
From your comments I have gathered that you are verifying if this method is working by checking for new entries in a database table. The data in the database could be missing for other reasons rather than the query. To verify, try a more simple web method, and go from there.
eg,
Html :
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitClick();" />
Javascript :
function submitClick() {
$.ajax({
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "default.aspx/getdata",
success: function (data) {
console.log(data);
alert("success" + data);
},
error: function () {
alert("something went wrong");
}
});
return false; // Note: the return false will prevent postback
}
C#
[System.Web.Services.WebMethod]
public static string getdata()
{
return "Hello World!";
}
If you do not see a success response, then the problem is indeed with your javascript, or rather with the site setup which is somehow preventing callbacks from javascript.
If the method succeeds then it is likely that your database insertion script is raising an error and you should step through it to see that cause.

Categories

Resources