Asp.net MVC + dropzoneJS file upload - asp.net

I use DropzoneJS with MVC. The file uploads fine, but action will not display another view, neither will display another view after redirected to another action. Just stays on the same view it was called from.
Action :
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
if(file != null)
{
string ext = Path.GetExtension(file.FileName);
if (file.ContentLength > 0 && ext == ".txt")
{
var fileName = Path.GetFileName(file.FileName);
if (fileName != null)
{
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
}
}
}
return View("Report");
// This will redirect to action but will not display another view either:
// return RedirectToAction("Report");
}
View called from:
<div id="dropzone">
<form action="/Dashboard/FileUpload" class="dropzone clickable" id="demo-upload" method="post" enctype="multipart/form-data">
</form>
</div>

you need to tell your browser to do the redirect, if you use dropzone to upload files asyncronsly. With a async call to your MVC controller, MVC can't tell the browser to change page. You can do a redirect in javascript after dropzone have uploaded the files with the complete event:
myDropzone.on("complete", function(file) {
window.location = "./Dashboard/Report/";
});

Related

Asp.net MVC5 application Runtime compilation

Is there any way to make my asp.net mvc5 applications runtime compilation like angular. In traditional way I change in .cshtml file save and press f5 to refresh running page then I get my change effect on page. But is there any way that can reload my page without pressing f5 in browser as like as angular application do.
Ajax refreshes the current page and gets the data from the server.
As shown in the code: ajax calls the Test action method under the PageLoad controller.
The background code is as follows:
public ActionResult Test()
{
var actionResult = default(JsonResult);
var stu = new STU();
this.UpdateModel(stu);
var tmp = string.Format("{0}{1} old from {2}", stu.Name, stu.Age, stu.City);
actionResult = new JsonResult()
{
Data = new { Message = tmp }
};
Thread.Sleep(5000);
return actionResult;
}
According to the student information passed by the front desk, return a string to ajax.
<form id="student_form">
<input type="submit" id="sub" value="submit" />
</form>
$(document).ready(function() {
$('#student_form').submit(function() {
$.ajax({
// ajax submit code....
});
return false;
});
});

Telerik Kendo UI ASP .NET Core Upload Inside Grid

I tried to add a custom column to Telerik Grid for uploading documents, but I am receiving 0 files in controller.
I think it's because name of form input field is different than parameter I receive in controller, Telerik adds column name (Document1) to left of upload filed name, see screenshot.
And this is my controller, see the parameter is file but in source of HTML the input field name is Document1.file
[HttpPost]
public async Task<ActionResult> SaveAsync(IEnumerable<IFormFile> file)
{
// The Name of the Upload component is "files"
if (file != null)
{
foreach (var f in file)
{
var fileContent = ContentDispositionHeaderValue.Parse(f.ContentDisposition);
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var physicalPath = Path.Combine(new HostingEnvironment().WebRootPath, "App_Data", fileName);
// The files are not actually saved in this demo
using (var fileStream = new FileStream(physicalPath, FileMode.Create))
{
await f.CopyToAsync(fileStream);
}
}
}
// Return an empty string to signify success
return Content("");
}
But I can't add a dot to parameter in controller!
How can I force it to for example name parameter as Document1_file?

asp.net mvc add partial view dynamically using ajax

I am new to ASP.NET and I have a problem to add a content to my main view. In HtmlBeginform I upload the file on a button click and after file loading I need to display partial view under my main view I donĀ“t know how to call ajax script properly.
My main view:
#using prvniAplikace.Models;
#using Chart.Mvc.ComplexChart;
#using Chart.Mvc.Extensions;
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("LoadFile", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="form-group" align="left">
<label for="exampleInputFile">Load File</label>
<input type="file" accept=".tcx" class="form-control-file" name="exampleInputFile" id="exampleInputFile" aria-describedby="fileHelp">
</div>
<div class="form-group" align="left">
<button class="btn btn-primary" type="submit" id="add" name="add" value="Add">Display</button>
</div>
}
#section Scripts {
<script type="text/javascript">
$("#add").on('click', function () {
$.ajax({
async: false,
url: '/Home/getContent'
}).success(function (partialView) {
$('#getContent').append(partialView);
});
});
</script>
}
View I want to add to a main view:
#{
ViewBag.Title = "getContent";
Layout = null;
}
<h2>Obsah</h2>
<p>Odstavec</p>
<p>#DateTime.Now.ToString()</p>
Controller:
namespace prvniAplikace.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult getContent()
{
return PartialView("~/Views/Home/AjaxRequest.cshtml");
}
[HttpPost]
public ActionResult LoadFile(HttpPostedFileBase exampleInputFile)
{
if (exampleInputFile.ContentLength > 0)
{
var fileName = Path.GetFileName(exampleInputFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
exampleInputFile.SaveAs(path);
string xmlFile = Server.MapPath(fileName);
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList nodes = doc.GetElementsByTagName("HeartRateBpm");
XmlNodeList nodes2 = doc.GetElementsByTagName("Time");
}
return RedirectToAction("Index");
}
}
}
As per your comment, you would like to load the partial view content via ajax after the index view is (re)loaded after the normal form submit you do to upload the file. To achieve this, you should make the ajax call in the document ready event. Since it is the same page/view user will see before and after the form submit, you should conditionally make the ajax call based on whether the page is loaded for your first GET request or for the GET request issued by the Redirect call in your http post action.
Since Http is stateless, there is no way for the GET action method to know whether this was called from the Redirect method call after successfully processing the submitted form (in your http post action). You may use TempData to address this problem. Before redirecting to the Index view, set a flag to the temp data dictionary which will be available in the next GET request.
[HttpPost]
public ActionResult LoadFile(HttpPostedFileBase exampleInputFile)
{
// your existing code here
TempData["Success"] = true;
return RedirectToAction("Index");
}
Now in your GET action, read this and pass it to view via ViewBag (or a view model property if you have one)
public ActionResult Index()
{
ViewBag.IsSuccess = TempData["Success"];
return View();
}
Now in the view, check this ViewBag item and if it exist and has true value, render the div in which we want to show the partial view content. You can take advantage of the the Url.Action helper method to generate the correct relative path to the action method which returns partial view and keep that in html5 data attribute in the div tag so we can use that in javascript later to make the ajax call.
So add this to your index view.
#if (ViewBag.IsSuccess!=null && ViewBag.IsSuccess)
{
<div data-url="#Url.Action("getContent", "Home")" id="myPartial"> </div>
}
Now all you need is the javascript code which makes the ajax call. Execute that in the document ready event. You can use the jQuery load method.
$(function(){
// Get the url from the data attribute of the div
var url = $("#myPartial").data("url");
// Make the ajax call using load method
$("#myPartial").load(url);
});

How to get filename to from controller in asp.net mvc

After I uploaded file using file uplaod control, and assigning it's name in controller, i need to get that file name in view. Also with that file name how to delete that file in my local drive(which is previously uploaded).
thanks.
check it please
public ActionResult SaveFile(HttpPostedFileBase FileUpload)
{
string path = string.Empty;
if (FileUpload != null)
if (FileUpload.ContentLength > 0)
{
fileName = Path.GetFileName(FileUpload.FileName);
path = Path.Combine(Server.MapPath("~/App_Data/Documents"), fileName);
FileUpload.SaveAs(path);
}
return View();
}
and don't forget to add enctype = "multipart/form-data" attribute to form
to can use this jQuery plugin to upload file via ajax jQuery File Upload in ASP.NET MVC

How to use FilePathResult.WriteFile?

Background
I have a secured folder containing secret report files (in pdf format). Each file corresponds to a single user.
My site is developed using Asp.net MVC 3 Razor.
When a user navigate to http://mydomain.com/UserProfile/Report, it invokes the GET-handling action method Report and return a view with a submit button Download Report.
When the user click the button, it invokes the POST-handling action method. Verification will be done in this action method. When the verification is successfully passed, the action method returns the requested file.
Question
Could you give me an example how to implement the POST-handling action method?
Here is the skeleton:
[HttpPost]
public ActionResult Report(/*any parameter I don't know*/)
{
if(!IsAuthenticated())
return RedirectToActionLink("SomeActionMethod","SomeController");
else
{
// what should I do here?
// Asssume my secret folder is d:\mydomain.com\secret and the public folder is d:\mydomain.com\httpdoc
}
}
Here is how you can return a file back to the client:
public FileContentResult Report(/*any parameter I don't know*/)
{
if(!IsAuthenticated())
return RedirectToActionLink("SomeActionMethod","SomeController");
else
{
// Read the file from your location into a byte array named content
Response.ContentType = "application/pdf";
return new FileContentResult(content, "application/pdf");
}
}
You can use the File method to return a FileContentResult
[HttpPost]
public FileContentResult Report()
{
if(!IsAuthenticated())
return RedirectToActionLink("SomeActionMethod","SomeController");
else
{
string path = #"d:\mydomain.com\secret\" + fileName;
return File(path, "application/pdf"); ////
}
}

Resources