I cant' seem to work uploadify on ASP.NET MVC3, I searched a lot and the code below seem to work fine, but not for me. When I try and upload it via html uploading method it works, not so much with uploadify. All libraries are included correctly.
<!-- Not working, HTTP ERROR 500 -->
<input id="file" type="file" name="file" />
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
// I tried to remove "/" at the start, does not help
'uploader': '/Scripts/u/uploadify.swf',
'script': '/home/upload',
'cancelImg': '/Scripts/u/cancel.png',
'folder': '/upload',
'auto': true,
'onError': function (event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
});
</script>
<!-- Working fine -->
<form action="home/upload" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
Home Controller Action
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var fileName = Path.GetFileName(file.FileName); // Object reference not set to an instance of an object. I get this if I try to upload via uploadify
file.SaveAs(Server.MapPath("~/upload/") + fileName);
return Content(fileName);
}
Didn't you debug your code? Didn't you notice that the file action argument is always null when the Upload action is hit? Your action argument is called file, so you need to specify that using the fileDataName option:
'fileDataName' : 'file',
By default uploadify uses Filedata, so if you don't want to specify this name you could also adapt your action argument name to match this:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase fileData)
{
var fileName = Path.GetFileName(fileData.FileName);
fileData.SaveAs(Path.Combine(Server.MapPath("~/upload/"), fileName));
return Content(fileName);
}
Also make sure that the ~/upload folder exists on your server. It doesn't when you create a new ASP.NET MVC application.
Another problem that I would like to point out with your code is that you have hardcoded absolutely all urls in your javascript. That's very bad and chances are that your application won't work when you deploy it in a virtual directory, say for example IIS.
In ASP.NET MVC you should always use url helpers when dealing with urls, just like that:
<script src="#Url.Content("~/Scripts/u/jquery.uploadify.v2.1.4.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/u/swfobject.js")" type="text/javascript"></script>
<input id="file_upload" type="file" name="file" />
<script type="text/javascript">
$(document).ready(function () {
$('#file_upload').uploadify({
'uploader': '#Url.Content("~/Scripts/u/uploadify.swf")',
'script': '#Url.Action("upload", "home")',
'cancelImg': '#Url.Content("~/Scripts/u/cancel.png")',
'folder': '#Url.Content("~/upload")',
'auto': true,
'onError': function (event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
});
</script>
Is use
HttpPostedFileBase file = Request.Files[0];
in my controller with Uploadify
Related
I am using DropZone on a RAZOR page in ASP.NET core 2.0 with other form inputs like this -
DzDemo.cshtml Page -
<form method="post" enctype="multipart/form-data">
<input type="text" id="Username" name="Username" />
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
</form>
<div>
<button type="submit" id="submit-all"> upload </button>
</div>
JS:-
Dropzone.options.myDropzone = {
url: "/DzDemo?handler=Upload",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
acceptedFiles: "image/*",
// paramName: myParamName,
init: function () {
var submitButton = document.querySelector("#submit-all");
var wrapperThis = this;
submitButton.addEventListener("click", function () {
wrapperThis.processQueue();
});
this.on('sendingmultiple', function (data, xhr, formData) {
formData.append("UserName", $("#Username").val());
});
this.on('error',
function (file, response) {
console.log(response);
alert(response);
});
}
};
DzDemo.cshtml.cs Page:-
[HttpPost]
public IActionResult OnPostUpload()
{
var data = Request.Form; //This is
return Page();
}
but I get 400 response from server and I am not able to process uploaded file server side Also it wont hot the Upload method on server side. Please help
One thing that will result in 400 using dropzone.js together with Razor Pages is if the AntiforgeryToken is missing from the form.
This is normally injected automatically but removing _viewimports or its taghelpers will prevent this.
To verify just add this line inside the <form/> element or look at the debug console for error messages.
#Html.AntiForgeryToken()
I got it working by setting the headers options
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }
Certainly, you need to have either at <form /> element or explicitly adding the #Html.AntiForgeryToken() in your page
Add this line in sendingmultiple, it will resolve your pb:
this.on('sendingmultiple', function (data, xhr, formData) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
});
I want to use the ()Load method. I have done it without a problem on PHP but now I want to do the same on ASP.net.
<script>
$(document).ready(function () {
$("#btn").click(function () {
$("#test").load("footershop.txt")
});
});
</script>
<section class="shop">
<footer>
<img src="#Url.Content("~/Images/klader.jpg")" alt="klader">
<div id="test" >
<p class="shoptext">text</p>
</div><br />
<button id="btn">Mejla oss</button>
</footer>
</section>
Here is my code in ASP.net. I put the "footershop.txt" in the App_Data folder. It does not show up. Where should I put the textfile in ASP?
you can use $.ajax instead of load to show the textfile content in the div. The txt file should be in the same directory path for the below code to work else you have to specify the actual path at the url property
<script>
$(document).ready(function () {
$("#btn").click(function () {
$.ajax({
url : "footershop.txt",
dataType: "text",
success : function (data) {
$("#test").html(data);
}
});
});
});
</script>
you should be testing it from a server not from local system as there might access issues in local to read the txt file.
i want to send my data from view to controller using ajax but I can't send the data to controller.
Thanks for your help.
That's my View code,
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>SignUp</title>
<link href="../../css/bootstrap.min.css" rel="stylesheet">
<link href="../../css/signin.css" rel="stylesheet">
<script type="text/javascript" src="../../js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#btnSignUp", function () {
var tcNo = document.getElementById('inputTcn').value;
var nameSurname = document.getElementById("Name").value;
var eMail = document.getElementById('Email').value;
var number = document.getElementById("PhoneNumber").value;
var secretQuestionAnswer = document.getElementById("inputSecretQuestionAnswer").value;
var password = document.getElementById('inputPassword').value;
var passwordVerify = document.getElementById("passwordVerify").value;
//var stateValue = document.getElementById("viewStates").value;
$.ajax({
type: 'POST',
url: '/Home/SignUp',
dataType: 'json',
data: {
'tcNo': tcNo,
'nameSurname': nameSurname,
'eMail': eMail,
'number': number,
'secretQuestionAnswer': secretQuestionAnswer,
'password': password,
'passwordVerify': passwordVerify,
'stateValue': stateValue
},
success: function (msg) {
alert("bsg");
},
error: function (msg) {
alert("2");
}
});
});
</script>
</head>
<body>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading"></h2>
<input id="inputTcn" class="form-control" placeholder="T.C. NO GİRİNİZ" required="" autofocus="">
<input id="Name" class="form-control" placeholder="ADINIZI SOYADINIZI GİRİNİZ" required="">
<input id="Email" class="form-control" placeholder="E-MAIL GİRİNİZ" required="">
<input id="PhoneNumber" class="form-control" placeholder="GSM NUMARANIZI GİRİNİZ" required="">
<input id="inputSecretQuestionAnswer" class="form-control" placeholder="ÖZEL SORUNUZUN CEVABINI GİRİN">
<input type="password" id="inputPassword" class="form-control" placeholder="ŞİFRENİZİ GİRİNİZ" required="">
<input type="password" id="passwordVerify" class="form-control" placeholder="ŞİFRENİZİ TEKRAR GİRİNİZ" required="">
#Html.DropDownList("viewStates")
<a id="btnSignUp" class="btn btn-lg btn-primary btn-block btn-danger">KAYIT OL</a>
</form>
</div>
</body>
</html>
and here that's my Controller,
[HttpPost]
public ActionResult SignUp(string tcNo, string nameSurname, string eMail, string number,
string secretQuestionAnswer, string password, string passwordVerify, string stateValue)
{
return View();
}
and I add data to my Dropdownlist at here,
[HttpGet]
public ActionResult SignUp()
{
var database = new KargoDB();
List<SelectListItem> stateList = (from s in database.States
select new SelectListItem
{
Text = s.Description,
Value = (s.State_id).ToString()
}).ToList();
ViewBag.viewStates = stateList;
return View();
}
500 error code means Internal server error. That means your server side code is crashing in the HttpPost Signup method.
If you open the network tab of your browser,and click on the response of the request you made, you will be able to see the response (Exception details returned by asp.net mvc). That will help you to identify the issue.
In your HttpPost action method, you called return View() ,which is going to return the Signup.cshtml razor view. But in the signup view, similar to our GET action, It is going to look for ViewBag.viewStates to render the state dropdown. But we did not set that in our HttpPost Signup method. So it will end up with a null reference exception when razor tries to render the view.
Remember, Http is stateless. One request does not have no idea what happened in the previous request. That means, the request for HttpPost action does not have any idea of the ViewBag items you set in the previous request(GET request).
Typically, for action methods which serves ajax posts, It is good to return a JSON response.
So instead of return View(), return a json structure.
[HttpPost]
public ActionResult SignUp(string tcNo, string nameSurname, string eMail,
string number,string secretQuestionAnswer, string password,
string passwordVerify, string stateValue)
{
return Json(new {status = "success"});
}
This is going to return a json structure like
{"status" : "success"}
And you can read that in your success event handler
success: function (msg) {
console.log(msg);
if(msg.status==="success")
{
alert("Saved");
}
}
Also, looks like you have a lot of parameters being posted to the Signup method, instead of writing so many params, you should use a view model.
Here is an example on how to do that.
Instead of returning a view from the controller return a JSON result and parse the result and bind it to the dropdown.
Since you are trying to retrieve data from the HTTPGet controller, you should be using the HTTP method of Get.
[HttpGet]
public JSONResult SignUp()
{
return Json(resultset, JsonRequestBehavior.AllowGet);
}
success: function (msg) {
// parse msg and bind to dropdown
},
Try using JSON.NET
For a detailed read
As mentioned above, http 500 is because of an exception in .Net code.Are you getting this in development. If so give the details of exception. You may attached to W3Wp.exe if you are doing it in some different way.
If this is hosted in dev / QA servers, use remote debugging mechanism. In production look at windows eventviewer. Sometimes you will see what is the exception. Once the exception is visible, just google or post it here.
http://www.codeproject.com/Articles/38132/Remote-IIS-Debugging-Debug-your-ASP-NET-Applicatio
What I am trying to do is to open up a jquery dialog.
What is happening is that I see the following html text vs the rendering of the form when it tries to open up the PartialView:
<form action="/Plt/FileUpload" method="post"><input data-val="true" data-val-number="The field PlNum must be a number." data-val-required="The PlNum field is required." id="PlNum" name="PlNum" type="hidden" value="36028" /> <div id="errMsg" >
</div>
<p>File upload for Pl# 36028</p>
<input type="file" name="file" />
<input type="submit" value="OK" />
</form>
Here is the controller action:
public ActionResult FileUpload(int id)
{
var model = new FileUpload { PlNum = id };
return PartialView(model);
}
This is what the view looks like for the PartialView:
#model Ph.Domain.Lb.Models.FileUpload
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("FileUpload", "Plts", FormMethod.Post, null))
{
#Html.HiddenFor(a => a.PlNum)
<div id="errMsg" >
#if (TempData["ErrMessage"] != null)
{
#TempData["ErrMessage"]
}
</div>
<p>File upload for Pl# #Model.PlNum</p>
<input type="file" name="file" />
<input type="submit" value="OK" />
}
This is what my ajax call looks like:
var url = '#Url.Action("FileUpload", "Plt")' + '?id=' + encodeURIComponent(rowid);
$.ajax({
url: url,
type: 'GET',
success: function(result) {
if (result.success) {
$('#dialog').dialog('close');
} else {
// refresh the dialog
$('#dialog').html(result);
}
}
To recap, the ajax call does reach the ActionResult but not sure when it tries to show the partial view it shows HTML vs the rendered html.
The issue here is that you are trying to load razor view which has not been rendered into the dialog's innerHTML. Instead what you should be doing is setting href property of the dialog to the URL.Action link, when creating the dialog. See the link below for an example.
http://www.matthidinger.com/archive/2011/02/22/Progressive-enhancement-tutorial-with-ASP-NET-MVC-3-and-jQuery.aspx
The other option, which is not very maintainable IMO, but which will work with way you are currently doing, is to return the raw HTML from the action method.
I think the first solution is better because the controller is not polluted with HTML string concatenation.
jQuery won't let you use a script inside .html(). You can do this by two ways:
Native DOM HTML injection instead:
$('#dialog')[0].innerHTML = result;
.
Or, setting it as a data attribute and loading it manually:
In view:
<form action="/Plt/FileUpload" ...
data-script="#Url.Content("~/Scripts/jquery.validate.min.js")"
... />
In JS:
$('#dialog').html(result);
var dialogScript = $('#dialog').children().first().data("script");
if(!!dialogScript) { $.getScript(dialogScript); };
Reference: http://api.jquery.com/jQuery.getScript/
.
Another way is use the load method, as in:
$("#dialog").load(url, null, function() {
// on a side note, put $("#dialog") in a variable and reuse it
$("#dialog").dialog();
});
Reference: http://api.jquery.com/load/
.
In the very case of jQuery validation, I'd consider adding it to the parent page itself. You'd expect it to be used in fair number of situations.
Using uploadify to auto submit a users files, in my controller method Request.Files["Name"] keeps returning null but request.form isn't null, I can see the file in request.form when I set a breakpoint and debug it. Am I missing something? I'm testing this on mvc2 but i plan on using it on mvc4.
<link href="../../Content/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="../../Scripts/jquery.uploadify.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#file_upload').uploadify({
'swf': '/Content/uploadify.swf',
'uploader': '/Home/UploadFile',
'auto': true
// Your options here
});
});
</script>
</head>
<body>
<%--<% using (Html.BeginForm("UploadFile", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>--%>
<input type="file" name="file_upload" id="file_upload" style="margin-bottom: 0px" />
<%-- <% } %>--%>
Controller Method:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
var theFile = Request.Files["file_upload"];
return Json("Success", JsonRequestBehavior.AllowGet);
}
If I add a submit button and then submit it it will work though. I need to be auto though without a submit button.
IIRC Uploadify uses fileData as parameter. So:
var theFile = Request.Files["fileData"];
or even better:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileData)
{
// The fileData parameter should normally contain the uploaded file
// so you don't need to be looking for it in Request.Files
return Json("Success", JsonRequestBehavior.AllowGet);
}
Of course if you are not happy with this name you could always customize it using the fileObjName setting.