file upload doesn't work in ASP.NET MVC4 - mobile template - c#

I am using C# and ASP.NET MVC4 for a web application (mobile template).
Now I have the following code in my view:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file">Upload:</label>
<input type="file" name="file" id="file"/>
<input type="submit" value="Upload" />
}
and this in my controller:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
string path = System.IO.Path.Combine(Server.MapPath("~/Content"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
return View();
}
when I run the application and try to upload a file, I get
"Object reference not set to an instance of an object." message in Visual Studio.
But I know that the code above works fine in ASP.NET MVC3 as I've used it before.
Can anyone help me with this?

Add this attribute to your form: data-ajax="false"
#using(Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype="multipart/form-data", data_ajax="false"})){
<label for="file">Upload:</label>
<input type="file" name="file" id="file"/>
<input type="submit" value="Upload" />
}

You don't have to use HttpPostedFileBase, as the matter of fact you don't have to receive any parameters in your [HttpPost] Action. You can get your file from the request like this as long as your form is set to enctype = "multipart/form-data" (which you already do):
var file = Request.Files[0];

Related

Ajax request doesn't send a file, but non-ajax does

The following code works:
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new { enctype = "multipart/form-data", data_ajax = "false" }))
{
#Html.AntiForgeryToken()
<input type="file" name="UploadedFile" />
<input type="submit" value="Upload" class="btn btn-primary" />
}
If I do Request.Files.Count I'll have 1 file in (given that I actually submitted a file in the form, of course), but if I change the data_ajax attribute to true, I never get a file (count is 0), neither through the Request.Files.Count, not through a parameter (where the list would be null) (ie:)
public ActionResult MyAction(IEnumerable<HttpPostedFileBase> files) {...}
Can anyone explain to me why does one actually submit the right form (with a file), but the other excludes the file from the request?

Cannot insert explicit value for identity column in table

Salaamun Alekum
I Am Getting NULL in file instance of action after posting a file in FORM
public ActionResult CreateDoctorProfile(HttpPostedFileBase file)
{
int LoggedInPersonID = Convert.ToInt32(Session["LoggedInPersonId"]);
erx_t_personnel PersonnelInformation = db.erx_t_personnel.Where(PersonnelInformation1 => PersonnelInformation1.Person_Id == LoggedInPersonID).FirstOrDefault();
return View(PersonnelInformation);
}
This Is My View
#model Doctors_Search_Engine.Models.erx_t_personnel
#{
ViewBag.Title = "Personnel Registration";
}
<h2>Personnel Registration</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<input type="file" name="file" />
<input type="submit" value="Create" class="btn btn-default" />
}
What Should I Do To Get Value In file Of Action Parameters. I Need Guidance On This
Thank You
The problem you have and the subject of your question are totally different. It's confusing.
If you are having an issue passing the file to your controller then your input file name should match the parameter in your controller method.
Change <input type="file" name="Image" /> to <input type="file" name="file" />
Or change your action result to:
public ActionResult CreateDoctorProfile(HttpPostedFileBase Image){}
You also need to set the encryption type to your form.
using (Html.BeginForm(new { enctype = "multipart/form-data" }))

How to upload file in ASP.NET razor

I want to upload a file in folder image.
I use ASP.NET with MVC4 and razor.
I have this in my View :
<div class="editor-label">
#Html.Label("Descriptif")
</div>
<div class="editor-field">
<input type="file" name="fDescriptif" />
#Html.ValidationMessageFor(model => model.fDescriptif)
</div>
[...]
<p>
<input type="submit" value="Create" />
</p>
In my controller :
[HttpPost]
public ActionResult Create(formation formation)
{
if (ModelState.IsValid)
{
db.formations.Add(formation);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(formation);
}
In my model :
public string fDescriptif { get; set; }
I have no idea what I must do to upload my file in my folder "image" and save just the name of my file in my database. When I validate my form it's my complete path who saved.
On your view make sure you have added enctype = "multipart/form-data" to your form tag, and then try like this:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmID" }))
And you can Get your file in Controller Action AS:
[HttpPost]
public ActionResult Create(formation formation,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
// Get your File from file
}
return View(formation);
}
you can find many questions like this, even on SO many answers have been given for this topic.
Here are 2 of the links. you should find your answer in this links. and many more other answers are there for this on SO. just google it, and you will find them.
https://stackoverflow.com/a/5193851/1629650
https://stackoverflow.com/a/15680783/1629650
Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):
#using (Html.BeginForm("ACTION", "CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
#Html.TextBoxFor(m => m.File, new { #type = "file" })
AND IN CONTROLLER
[HttpPost]
public ActionResult ACTION(ViewModels.Model taskModel)
{
string path = #"D:\Projects\TestApps\uploadedDocs\";
if (taskModel.File != null) {
taskModel.File.SaveAs(path +taskModel.TaskTitle
+ taskModel.File.FileName);
newUserProject.DocumentTitle = taskModel.TaskTitle
+ taskModel.File.FileName;
newUserProject.DocumentPath = path + taskModel.File.FileName;
}
}
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
And your controller should be as below
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}

Trouble uploading file in MVC3

I have the following image upload code and controller. The hidden ID is POSTing successfully, but the image remains null.
The form:
#using(Html.BeginForm()){
<input type="hidden" name="merchandiseId" id="id" value="#ViewBag.Id"/>
<input type="file" name="image" id="image" />
<input type="submit" />
}
The controller:
[HttpPost]
public ActionResult AddImage(int merchandiseId, HttpPostedFileBase image)
Debugging and stepping in verifies that image is null while merchandiseId has the correct value.
You need to add the enctype = "multipart/form-data" in your form. otherwise no file will be uploaded.
An example
#using (Html.BeginForm("UploadAction", "MyController", new { Model.Id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="myFile">
<button type="submit>Upload</button>
}
Try adding new { enctype = "multipart/form-data" }to your form

Get files for each language in model (MVC 3) using HttpContext to save them in separate table

I have this simple piece of HTML code:
<div>
<input type="file" name="english-file" />
</div>
<div>
<input type="file" name="french-file" />
</div>
I used in my model, the following C# line code:
object receivedFiles = HttpContext.Current.Request.Params["english-file"];
but that object returns null always.
Of course that I can use HttpContext.Current.Request.Files but I want to sepparate files by languages (the above HTML code is simple but someone could add more files to english than french with +Add files button) and save them in sepparate table.
How could I do that?
That's not how files are uploaded. You should look in Request.Files["english-file"] after setting the proper enctype on the form.
Let's take an example:
#using (Html.BeginForm("upload", "somecontroller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="english" />
</div>
<div>
<input type="file" name="french" />
</div>
<button type="submit">Upload</button>
}
and in the controller action:
[HttpPost]
public ActionResult Upload()
{
var englishFile = Request.Files["english"];
var frenchFile = Request.Files["french"];
...
}
or even better:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase english, HttpPostedFileBase french)
{
...
}
or even better:
[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
...
}
assuming you adjust the names of the file inputs:
#using (Html.BeginForm("upload", "somecontroller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="files" />
</div>
<div>
<input type="file" name="files" />
</div>
<button type="submit">Upload</button>
}
I also invite you to read the following blog post.

Categories