Uploaded file is null - c#

In ASP.NET MVC4, a file-upload view is always sending null to the controller.
I have no idea why, I don't know how to fix it and searching has proven unfruitful...
Controller method:
[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase file)
{}
View:
#using (Html.BeginForm("uploadCustomImage", "W", new { id=ViewBag.id }, FormMethod.Post, new { enctype = "multipart/form-data", name="uploadingimage" }))
{
<input name="file" id="file" type="file" />
#Html.SubmitButton()
}
It enters into the controller fine, so routing is all good. But file is always null. I've tried several different things: renaming the input/object, not using a file argument and calling this:
HttpPostedFileBase file = Request.Files["file"];
(which also turns out null)
I tried including a formcollection as a parameter (with and without unnecessary form elements). Still this file is null.
I am of course selecting a file before I press submit =P I've tried multiple files; with very basic filenames (no weird unicode, even no spaces) and also weirder ones. Large files, small files.
Everything comes out null! Where have I gone wrong?

your names don't line up... you need to model bind your file control called "postedFile" in your controller

Try it like this:
#using (Html.BeginForm("uploadCustomImage", "W", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="fileToUpload" type="file" />
<input type="submit" />
}
[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase fileToUpload)
{}
[EDIT]
I've just implemented an upload feature in a project I'm working on and it works.
#using (Html.BeginForm("Import", "MY_CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="UploadedXlsFile" name="UploadedXlsFile"/>
<input type="submit" id="Submit" name="Submit" value="Submit"/>
}
public ActionResult Import()
{
if (Request.Files["UploadedXlsFile"].ContentLength > 0)
{
.............Do stuff ................
}
}
The previous code works for me. If I put a break point inside the Action method, I can see the file isn't null.

Related

How do you pass post form variables in ASP.NET C#/Razor?

I'm new to C#/Razor and don't know how to pass form data using the post method. Here's what I've tried:
In login.cshtml:
string username = Request.Form["username"];
string password = Request.Form["password"];
And
string username = Request.Form.Get("username");
string password = Request.Form.Get("password");
In _AppStart.cshtml, I tried:
AppState["username"] = HttpContext.Current.Request.Form["username"];
AppState["password"] = HttpContext.Current.Request.Form["password"];
All return nothing.
Here's the form elements in login.cshtml:
<form action="index.cshtml" method="post" data-ajax="false">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
If you need to pass data between MVC controller and View then you have to let Asp know which action an controller to call.
To accomplish this you could use something like BeginForms in razor an specify the needed information.
This would look like this:
#Html.BeginForm("YourAction", "YourController", FormMethod.Post){
#Html.TextBoxFor(employee => employee.FirstName);
#Html.TextBoxFor(employee => employee.LastName);
#Html.TextBoxFor(employee => employee.Age);
<input type="submit" value="Edit" />
}
Following this snippet you can see that you need A Controller and you name an ActionResult according to the name given here furthermore you can specify if you want to have the action only when posting or only for get forms
An possibile exemple could be the edit like the following code
[HttpPost]
public ActionResult YourAction(Employee emp)
{
if (ModelState.IsValid)
{
// do smth.
}
return View("Name Of the view");
}
Note you need to define this in your Controller and that the Attribute HttpPost lets Asp know that this is a post only ActionResult. This means that only post requests can use this Method. Furthermore
if you wish to have both get and post requests available for this ActionResult then you can simply delete the Attribute then per default it will be available in get and set requests.
You could look at this forum
entry
in Input Type "submit add formaction="ActionMethodName"
#using (Html.BeginForm("MethodName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="postedFile"/>
<input type="submit" **formaction="UploadData"** value="UploadData"/>
}

How to keep my model data when do GET>POST>REDIRECT to upload a file?

I want to create a register form using MVC which include a profile photo. I don't want to add record for people before completing the form (including profile photo upload). Also I want my UploadImage view and controller to be re-usable for many forms (not just this form). I pass three variables to my upload form through ActionLink: RedirectAction (RA), RedirectController (RC), and dataname and the procedure goes like this:
I store RA, RC, dataname in ViewBag, then put them in hidden <input> tags to be submitted when POSTing the file
// GET: UploadImage/Upload
public ActionResult Upload(string RA, string RC, string dataname)
{
ViewBag.RedirectAction = RA;
ViewBag.RedirectController = RC;
ViewBag.DataName = dataname;
return View();
}
Put these lines in my Upload.cshtml (View):
#using (Html.BeginForm("Upload", "UploadImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="hidden" name="RA" value="#ViewBag.RedirectAction" />
<input type="hidden" name="RC" value="#ViewBag.RedirectController" />
<input type="hidden" name="dataname" value="#ViewBag.DataName" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
Store the filename in TempData with dataname as the Key and redirect to /RC/RA:
// POST: UploadImage/Upload/
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string RA , string RC , string dataname)
{
var filepath = "C:/myfilename.jpg";
TempData.Add(dataname, filepath);
return RedirectToAction(RA,RC);
}
And get my filepath by utilizing TempData in my register form:
#if (TempData.Keys.Contains("MyData")) {
<div class="form-group">
<p>#TempData["MyData"].ToString()</p>
</div>}
The code works just fine, but the essential caveat is that I don't want other completed fields to get lost when redirected to the register form. How can I solve this problem ?
One option is to stick the data in the session. Another option would be to use a separate database table to hold in-progress registration data.

How to POST a file to asp.net mvc app? [duplicate]

This question already has answers here:
File Upload ASP.NET MVC 3.0
(23 answers)
Closed 9 years ago.
I'm posting a simple text file to an asp.net MVC app. When I post using the form below, the form parameter is not null. But file is. Any ideas what I'm doing wrong?
<form method=post action="http://localhost/Home/ProcessIt"
enctype="application/x-www-form-urlencoded">
<input type=file id="thefile" name="thefile" />
<input type="submit" name="Submit" />
</form>
In the asp.net mvc app:
[HttpPost]
public ActionResult ProcessIt(FormCollection thefile)
{
HttpPostedFileBase file = Request.Files["thefile"];
...
}
This works for me:
View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Controller:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// then save on the server...
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
Need to change the enctype to multipart/form-data: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2

HttpPostedFileBase always returns null

I am using MVC 4 and I tried for upload file concept.
Here is my code:
<div class="complianceSubDiv">
<div class="complianceLeftDiv">
#Html.Label("Upload the file")
</div>
<div class="complianceRightDiv">
<input type="file" id="file" name="file" />
</div>
</div>
My controller code like
[HttpPost]
public ActionResult ManageDocument(DocumentModel documentModel, HttpPostedFileBase file)
{
//some code
}
But the HttpPostedFileBase file always returns null. I have searched more answers in StackOverflow and other websites and I got the working answer is parameter of HttpPostedFileBase variable name and fileupload control name are same . So I put the same name on all sides, but it returns null only.
Anyone help to me?
Finally i got it
Now i replaced for #using (Html.BeginForm())
to
#using (Html.BeginForm("ManageDocument", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
It's working !
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase myFile)
{
myFile = Request.Files["file"];
if (myFile != null && myFile.ContentLength > 0)
{
// your code ....
}
return View();
}
You can use "Request.Files" to get the selected file, above is the code.

uploading an image

Recently I am getting interested in image manipulation. But I am stuck just at the beginning of the long journey.
I have a problem in uploading an image in asp.net mvc3(razor view) project.
Can any one suggest me a basic sample/tutorial how to do it so.
To upload an image just call this in your html.
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" />
}
Be sure to have enctype = "multipart/form-data" or your file won't be uploaded.
Then from the controller just handle the Request.Files of accept directly a HttpPostedFileBase
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//file handling logic
file.SaveAs(/* your path here */);
}
return RedirectToAction("Index");
}
Remember also that classic file upload don't work with ajax calls. If that is the case you must use a plugins like this one

Categories

Resources