Uploading file in with ASP.NET MVC3 (OpenFileDialog alternative) - c#

I'm trying to replicate some webforms functionality that uploads a csv file in an MVC3 project and am coming unstuck. I have the following requirements:
(Short version is that I need something similar to the Filter, InitialDirectory and preferably but not necessarily, the MultiSelect properties of the System.Windows.Controls.OpenFileDialog class for MVC3)
Single button displayed that opens the open file dialog
Upload begins when open is clicked in the dialog
The file type in the dialog should be restricted to csv, txt and All files
The initial directory should be able to be set depending on user preferences
I've used jQuery for the first two requirements (shown below) but am not if this is the best way or how to accomplish the last two.
View:
#using (Html.BeginForm("Import", "Date", FormMethod.Post, new { enctype = "multipart/form-data", id="fileUpload" }))
{
<input type="file" name="file" id="file" style="display: none;" />
<input type="button" id="import" value="Import" />
}
<script type="text/javascript">
$(document).ready(function () {
$('#file').change(function () {
$('#fileUpload').submit();
});
$('#import').click(function () {
$('#file').trigger('click');
});
});
</script>
Controller:
[HttpPost]
public ActionResult Import(HttpPostedFileBase file)
{
// do stuff
}
Any ideas?

It's not possible to do unless you use a Flash or Silverlight plugin. I use Uploadify and it should do everything you need.

Related

limit number of files to be uploaded in mvc

In my MVC application, i have information upload form. Here user can upload videos and images. To do this i have created to file controls, one for videos and one for images. Here user should be only able to upload at max 2 videos and at max 5 images for single form. Can any one suggest me how can i limit the user to upload number of files. i.e. if only 2 videos and 5 images also where should i implement this for best use? in controller or using javascript?
The MVC file upload approach:
<input type="file" name="file" id="file" />
This passes a HttpPostedFileBase to the controller or if you have multiple IEnumerable<HttpPostedFileBase>. You can then evaluate the number of files and file types and return any functionality/messages back to the user.
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {...
Or
<input type="file" name="files" id="file" />
<input type="file" name="files" id="file" />
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {...
I tried using javascript
File upload control :
<input type="file" id="t" name="t" onchange="checkFilesCount(this)" multiple>
javascript code :
function checkFilesCount(id) {
if(id.files.length > 5)
{
alert('you cant upload files more than 5');
document.getElementById("t").value = "";
}
}

Controller returning PartialView overwriting entire View

I'm POSTing and trying to re-load a partial view with the new data using Ajax like this:
Index.cshtml
<div id="left-column">
#Html.Partial("~/Views/Project/_ProjectList.cshtml", Model.ProjectList)
</div>
~/Views/Project/_ProjectList.cshtml
#using (Ajax.BeginForm("Create", "Project", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "left-column"
}))
{
<h3>Create a new project</h3>
<div class="form-group">
<label for="new-project-name">Name</label>
<input type="text" class="form-control" id="new-project-name" name="Name" placeholder="Example" />
</div>
<button type="submit" class="btn btn-primary">Create Project</button>
Cancel
}
Then my Controller returns the PartialView after some db work:
[HttpPost]
public PartialViewResult Create(Project newProject)
{
db.Projects.Add(newProject);
db.SaveChanges();
var projectList = db.ProjectLists.SingleOrDefault(pl => pl.Id == 1);
return PartialView("~/Views/Project/_ProjectList.cshtml", projectList);
}
I would expect the _ProjectList partial view to load into the #left-column element with the new projectList passed in by the Controller, but instead, the entire View is being overwritten, so the entire body of the new HTML source looks basically like this:
<body>
<!-- all the stuff from the _ProjectList partial -->
</body>
It's worth noting that after the partial view returns, the URL reads /Project/Create, which I wouldn't expect.
I've included jquery-validate and jquery-validate-unobtrusive, and the console isn't showing any errors, so that shouldn't be the problem.
Any idea what's going on?
When using Ajax.BeginForm helper method to do ajax form posting, you need to include the jquery.unobtrusive-ajax.js file as well. This file has the code to handle the submit button click event and send the form asynchronously rather than doing the normal form submit.
If you do not include this file, the form submit will be normal. My guess is that you missed to include this file and hence missing the ajaxified form submit experience.
So make sure to load this file after jQuery
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Here is the link to nuget page if you want to add this file via nuget package manager.
Benjy got it in a comment above. It was a jQuery version issue. I'm running 3.1.0, and jquery.unobtrusive-ajax stopped working with jQuery version 1.9.

How do I Return my View and call a btn function on it's form?

I have a Controller myCustomers with a View.
The controller has two useful ActionResults; namely loadDataTotbl and CreatePDF.
(Filestream with Itextsharp).
loadDataTotbl loads the View fine which is simply a db obj via LINQ.
The View has a table in a form with some elements and a create PDF button e.g.:
#using (Html.BeginForm("CreatePDF", "myCustomers", FormMethod.Post))
{
<form>
<table>
#foreach (var cn in Model)
{
<input type="text" value="#pn.CustomerName" name="cNameVal" />
}
<input type="submit" value="Download the PDF" />
</table>
</form>
}
It works fine. When I hit the button, PDF gets created.
How do I create the PDF but hide/bypass this view? Please note my View has to remain as I strip it's headers and values and use them in CreatePDF action to create and design my PDF.
Do I need partial view? How would it work here?
I don't think I can hide views if they have data I need.
How do I do this?

MVC .NET Refresh (Update) PartialView witout AJAX

I have a page with partial view that contains DevEx ComboBox with Add button and DevEx GridView ( I omitted GridView code). Page is showing properly with that partial view, only I have a problem with refreshing it.
//_ProductAppsGridViewPartial
<div class="form-horizontal">
<h4>Apps</h4>
#using (Html.BeginForm("AppsGridViewPartialAddNew", "Products", new { ProductID = ViewBag.ProductID }))
{
<div class="form-group">
<h5>Add new App:</h5>
#Html.DevExpress().ComboBox(settings =>
{
//..do some settings for ComboBox - some code omitted
settings.Properties.ValueField = "ApplicationID";
settings.Properties.TextField = "Name";
}).BindList(Model.AppsNotInProduct).GetHtml()
<input type="submit" value="Add" class="btn btn-default" />
</div>
}
</div>
I have action on my controller that adds selected app in database and returns a PartialView with the same (but refreshed) model, but response shows only that partial View. Here is a part of Controller's action that returns PartialView after updating database:
public ActionResult ProductAppsGridViewPartialAddNew(int ProductID)
{
//....update DB code - WORKS FINE
..
var model = GetProductAppsPartialModel(ProductID);
ViewBag.ProductID = ProductID;
ViewBag.CanEdit = true;
return PartialView("_ProductAppsGridViewPartial", model);
}
Is it possible to refresh a partial view wihout AJAX, maybe something i wrote above? So the main problem here is that i get new page showing only a partial view.
To refresh part of a page you will need to use ajax to replace only the needed content. You will also need to use JavaScript to re-render the HTML contained in the partial. MVC comes with some ajax helpers or you can do it yourself with jquery. At the moment the action result is returning the partial as requested but the browser is being told it is receiving a whole new page and is displaying as such.
Adding this link to Microsoft ajax to show some of your options.
I would use jquery and do this yourself. Also try to remember that mvc is a server side framework to help you return http messages to the browser. You are trying to manipulate things client side. Live client side updates always need ajax to get data. Replacing items in the DOM needs some form of JavaScript. Libraries like jquery make this a lot easier. Have a look at jquery ajax here.
I think you need to try this code.
Note here we need to keep ajax call for update the partial view
#using (Ajax.BeginForm("ActionName", "Controller", new { model = #Model.ID },
new AjaxOptions
{
OnSuccess = "onSuccessRefresh "
}))
{
<table>
<td>
</td>
<td> <input type="button" value="AddValue" /> </td>
</table>
}
Handle the code onsuccess event using jquery:-
function onSuccessRefresh {
// refersh your page or table
}
This is not the full code. but I think it will help to you

How to submit a file without POSTing it to the server?

I'd like my users to be able to upload a picture to my server and without having them switch pages have that image bounced back to a div on that site once the upload has finished.
This is for a "Change your profile picture" page. I need to get the picture back so I can invoke the jCrop jquery library on it so they can crop the picture to their liking.
Here's what I have so far:
#{
ViewBag.Title = "Profile Picture";
}
<h1>Please choose your new profile picture.</h1>
<input type="file" name="file" />
<input type="submit" value="OK" />
If I put in the #using BeginForm the form is posted back and the page loads somewhere new. I don't want this behavior. How do I do this with AJAX without reloading?
You can't submit a file via ajax unless your browser supports the file API. https://developer.mozilla.org/en/using_files_from_web_applications
You can create an iframe and use that to submit your image.
How can I upload files asynchronously?

Categories

Resources