HttpPostedFileBase always return null in ASP.NET MVC - asp.net-mvc

I have a problem when I upload a file in ASP.NET MVC.
My code is below:
View:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index2</h2>
#using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" />
<input type="submit" />
}
Controller:
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
But uploadFile always returns null.
Can anyone figure out why??

#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index2</h2>
#using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="uploadFile"/>
<input type="submit" />
}
you have to provide name to input type file to uploadFile in order to model binding work in ASP.net mvc and also make sure that name of your input type file and argument name of HttpPostedFileBase is identical.

I had tried most of the solutions posted online for this topic, but found it better to use a workaround instead..
It really didn't matter what I did the HttpPostedFileBase and/or HttpPostedFile were always null. Using the HttpContext.Request.Files collection seemed to work with no hassles at all.
e.g.
if (HttpContext.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Request.Files[0];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath =(HttpContext.Server.MapPath("~/UploadedFiles") + httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(#"\")));
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
In the above example I only grab the first file, but it is just a matter of looping though the collection to save all files.
HTH
Rob

In my scenario the problem was with id attribute, I had this:
<input type="file" name="file1" id="file1" />
The soultion was to remove id:
<input type="file" name="file1" />

While not the answer to this specific user, I would like to point out that HTML requires that the form tag has an enctype attribute with the value multipart/form-data. And of course both the attribute and it's value must be correct.
For mvc, this means that when using beginform, you should use the version with the htmlAttributes parameter

There can be another scenario also. In my case, I was getting this issue because I was directly rendering script tag in my MVC view and IE is giving issue there.
Correct code in view should be as below:
#section scripts
{
<script>
$(document).ready(function () {
$('.fileinput').fileinput();
...
}

You need to use Razor code to set Name of the input file.
<input type="file" name="#Html.Namefor(m => m.propertyName)">

Related

Update and ASP.NET MVC model on button click

I'm new to ASP.NET MVC. I'm trying to update model on button click with no success: every time I push the button an HttpGet controller method is invoked.
Here is my markup
#model DataInterface.Model.Entry
<button onclick="location.href='#Url.Action("Survey")'">Finish survey</button>
Here is Controller code
[HttpGet]
public ActionResult Survey()
{
var entry = new Entry();
return View(entry);
}
[HttpPost]
public ActionResult Survey(Entry newEntry)
{
// save newEntry to database
}
When I click button HttpGet method is invoked. Why?
It is bad to be a rookie)
Thanks to all!
If you access a URL without explicitly specifying the HTTP method, ASP.NET MVC will assume a GET request. To change this, you can add a form and send it:
#using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
<input type="submit" value="Finish survey" />
}
If you do this, your POST method will be invoked. The Entry parameter, however, will be empty, since you do not specify any values to send along with the request. The easiest way to do so is by specifying input fields, e.g. text inputs, dropdown, checkboxes etc.
#using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
#Html.TextBoxFor(m => m.Title)
<input type="submit" value="Finish survey" />
}
If you have the object stored on the server somewhere and only want to finish it off by writing it into the database or changing its status, you could pass the Id of the object (or some temporary Id) along the post request and make the controller method work only with the Id:
#using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
#Html.HiddenFor(m => m.Id)
<input type="submit" value="Finish survey" />
}
[HttpPost]
public ActionResult Survey(Entry newEntry)
{
// newEntry.Id will be set here
}
#using (Html.BeginForm("Survey", "<ControllerName>", FormMethod.Post))
{
<input type="submit" value="Finish survey" />
}
you must declare your form
#model DataInterface.Model.Entry
#using (Html.BeginForm("action", "Controlleur", FormMethod.Post, new {#class = "form", id = "RequestForm" }))
{
<input type="submit" value="Finish survey" />
}

How can I get both a model and HttpPostedFileBase into a controller?

I've looked quite a bit online, and every example I see explains how to get IEnumerable<HttpPostedFileBase> into a controller, OR how to get a model, but not both.
What I want is something like:
<form>
<input type="text" name="Stored file name>
<input type="file" multiple="multiple" name="files>
<input type="submit">
</form>
with controller
[ActionName("Index"), HttpPost]
public ActionResult IndexPost(Models.MyModel mdl, IEnumerable<HttpPostedFileBase> files)
{
// Do some something with the data in mdl and files here
return RedirectToAction("Index");
}
But every way I try to implement this, it comes back 'no parameterless handler found'. It works fine if I don't include the model.
Am I missing something really obvious?
I guess you couldn't find Darin's this post. It's not exactly about passing model with HttpPostedFileBase but if you undrerstand the behavior the it's easy to do that.
See below example.
View
#model WebApplication2.Models.MyModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(m => m.Id)
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Action Method
[HttpPost]
public ActionResult Index(MyModel model, HttpPostedFileBase file)
{
if (file != null)
{
//do your stuff here
}
return View();
}

MVC ERROR Illegal characters in path.

can someone tell me if im on the right track? Im trying to display my query but i get an error. I have two textbox with the same parameter and that parameter is declared as an IEnumerable.
[HttpPost]
public ActionResult Orders1(IEnumerable<int> order)
{
using (CostcoEntities1 context = new CostcoEntities1())
{
var query = string.Empty;
foreach (var orderID in order)
{
query = (from a in context.CM_Checkout_Details
where a.CheckoutDetails_ID == orderID
select a).ToString();
}
return View(query);
}
}
this is what my controller looks like..
I am trying to read the two numbers(Id) in the text box and diplay data based on those id.
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order")<br />
#Html.TextBox("order")
<input type="submit" value="Submit" />
}
First thing, change the names of the textboxes so that they are not the same:
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order1")<br />
#Html.TextBox("order2")
<input type="submit" value="Submit" />
}
Next, change the signature of your action method:
[HttpPost]
public ActionResult Orders1(string order1, string order2)
MVC's model binding will try to match order1 and order2 to stuff in Request.Form, for example, which should pick up the textbox values.

How to get file from HDD to Bitmap object [ASP MVC 3]?

I'm new to ASP MVC and I've been trying to upload a bitmap file from hard drive to a C# Bitmap object, which I would later assign to my Model.
The view (cshtml file) looks like this:
<form action = "DisplayAddedPicture" method=post>
<input type=file name="Picture" id = "Picture"/>
<input type=submit value="Send!" />
</form>
And the DisplayAddedPicture method from controller:
[HttpPost]
public ActionResult DisplayAddedPicture()
{
HttpPostedFileBase File = Request.Files["Picture"];
if (File == null) throw new Exception("NullArgument :( ");
// file stream to byte[]
MemoryStream target = new MemoryStream();
File.InputStream.CopyTo(target);
byte[] TempByteArray = target.ToArray();
// byte[] to Bitmap
ImageConverter imageConverter = new ImageConverter();
Image TempImage = (Image)imageConverter.ConvertFrom(TempByteArray);
Bitmap FinalBitmap = new Bitmap(TempImage);
// (...)
}
It turns out that every time all I get is an Exception, as the HttpPostedFileBase object is always null. Is there any flow in my logic (apart from all of those conversions which come afterwards, I know they're messy) or is there any other way to solve this?
Try this
In your View,
#using (Html.BeginForm("DisplayAddedPicture", "YourControllerName",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type=file name="Picture" id = "Picture"/>
<input type=submit value="Send!" />
}
And the Action method
[HttpPost]
public ActionResult DisplayAddedPicture(HttpPostedFileBase Picture)
{
if (Picture!= null && Picture.ContentLength > 0)
{
//Do some thing with the Picture object
//try to save the file here now.
//After saving follow the PRG pattter (do a redirect)
//return RedirectToAction("Uploaded");
}
return View();
}
Try adding the following to your form tag: enctype="multipart/form-data"
<form method="post" action="DisplayAddedPicture" enctype="multipart/form-data">
<input type=file name="Picture" id = "Picture"/>
<input type=submit value="Send!" />
</form>

Why Ajax.BeginForm does not pass form values?

I'm trying to show a partial view via calling Ajax.BeginForm, but I can't receive the values of my form(I need to get the value of hidden input, bookId, in controller, e.g 5).
// View
#using (Ajax.BeginForm("Detail", "Books", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "ShowBookDiv" }))
{
<input type="hidden" id="bookId" value="5" />
<input type="submit" id="sBtn" value="Details" />
}
// Controller
[HttpGet]
public ActionResult Detail(string bookId)
{
if (Request.IsAjaxRequest())
{
var a = Request["bookId"].ToString();
// some code to get details
return PartialView("ShowBooks", details);
}
...
}
When I trace the code in Controller bookId is null!
I've added the "name" property to hidden field and it works !!! really strange!
<input type="hidden" name="bookId" id="bookId" value="5" />
Ajax.BeginForm is a pain, IMO.
I would Use $.ajax from JQuery Ajax API :
http://api.jquery.com/jQuery.ajax
here is a good example for you to see how it works :
http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views
Posting the whole form requires a little bit of work (in terms of validation, etc.) but you will have complete control over the action if you are good with JavaScript.

Resources