I added an input file field but it's always null on the controller. What am I missing?
Here's the code for both my view and controller.
view:
...
#using (Html.BeginForm())
{
...
<input type=file name="file" id="file" class="post-attachment" />
...
}
controller:
[HttpPost]
public ViewResult _Details(HttpPostedFileBase file, ViewTopic viewTopic, string SearchField, string submitBtn)
{
// save file to server
if (file != null && file.ContentLength > 0)
{
var fileName = DateTime.Today.ToString("yy.MM.dd") + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Attachments"), fileName);
file.SaveAs(path);
}
...
}
You need to explicitly set the enctype of the form:
#using(Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}
You need to change your form to something like -
#using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<input type="file" id="fileUpload" name="fileUpload"/>
</p>
<p>
<input type="submit" value="Upload file" /></p>
}
There's a load more info (including the sample above) in this question - Html helper for <input type="file" />
Related
I have a code in editform like this.
#using (Html.BeginForm("Bind", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<img id="sp" src="/Student/RetrieveImage/model.StudentID" alt="Photo" height=100 width=200 />
<input type="file" name="ImageData" id="ImageData" onchange="DI();"/>
}
And this in Student Controller
HttpPostedFileBase file;
public ActionResult Bind()
{
file = Request.Files["ImageData"];
file = Request.Files["ImageData"];
return RedirectToAction("StudentEdit");
}
The begin form is found in editform which is a partial form. What I need is to fire the Bind Action when file is selected from input file. How can I do this?
You are working with an form(html element) to upload the image(with HTTP POST verb), in your example you have two main options to proceed with the upload:
1'st option: Create a submit input inside the form
#using (Html.BeginForm("Bind", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="DI();"/>
<input type="submit" name="submitbutton" value="Upload" />
}
2'nd option: submit the form with javascript, in this example I used the event that you created at the file element:
#using (Html.BeginForm("Bind", "Student", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="this.form.submit();"/>
}
my controller Have 2 Actions :
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}
ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}
//
// GET: /AdultLiteracyTeachers/Details/5
public ActionResult Details(int id = 0)
{
AdulLiteracyTeachers adulliteracyteachers = db.AdulLiteracyTeachers.Find(id);
if (adulliteracyteachers == null)
{
return HttpNotFound();
}
return View(adulliteracyteachers);
}
my view in Create.cshtml
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" }))
<input type="file" name="files" value="Upload Image" />
<input name="Upload" type="submit" value="Create" />
Problem is
only upload is working when I submit button others create etc not working
how to call multiple actions in single form create button ?
I believe you can use the beginform multiple times like this:
#using (Html.BeginForm(Upload, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input type="submit" name="files" value="Upload Image" />
}
#using (Html.BeginForm(Details, ControllerName, FormMethod.Post, new { enctype = "multipart/form-data" })){
<input name="Upload" type="submit" value="Create" />
}
and make sure that the button type="submit".
I have the following _CreateOrEditPartial partial view which contain a text & a file upload:-
#model TMS.Models.DataCenter
#* This partial view defines form fields that will appear when creating and editing entities *#
#Html.AntiForgeryToken()
<div>
<span class="f">Name </span>
#Html.EditorFor(model=>model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div>
<span class="f">Data Center Picture </span>
<input type="file" name="DataCenterfile" />
</div>
and the following main view :-
#using (Html.BeginForm("Create","DataCenter", FormMethod.Post))
{
#Html.ValidationSummary(true)
#Html.Partial("_CreateOrEdit", Model)
<input type="submit" value="Create" class="btn btn-primary"/>
}
Which will call the following ActionMethod:-
[HttpPost]
[ValidateAntiForgeryToken]
[CheckUserPermissions(Action = "Edit", Model = "DataCenter")]
public ActionResult Create(DataCenter dc, HttpPostedFileBase DataCenterfile)
{
// Verify that the user selected a file
if (DataCenterfile != null && DataCenterfile.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(DataCenterfile.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
DataCenterfile.SaveAs(path);
}
but the datacenterfile will always be null .. can anyone advice what is causing this problem?
Thanks
You forgot to add the enctype attribute to your form.
Something like this:
#using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
About enctype attribute: What does enctype='multipart/form-data' mean?
I simply tried this, but its not working, what is the problem in it,
MY index page:
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/from- data" }))
{
<div>
<h1 style="align-content: center; color: blueviolet">Application to upload files</h1>
</div>
<div>
<input type="file" id="file" name="file" />
<br />
<input type="submit" id="load" name="submit" value="Submit" />
</div>
}
And My controller is,
[HttpPost]
public ActionResult Upload()
{
string path = #"~/Content/Upload";
HttpPostedFileBase file = Request.Files["file"];
if (file != null)
file.SaveAs(path + file.FileName);
return Content("Sucess");
}
The path you are attempting to save your file to looks wrong. Try with MapPath:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
string path = Server.MapPath("~/Content/Upload");
if (file != null)
{
file.SaveAs(Path.Combine(path, file.FileName));
}
return Content("Sucess");
}
Also make sure that you have used the correct enctype attribute in your form:
enctype = "multipart/form-data"
instead of:
enctype = "multipart/from- data"
View:
#using (Html.BeginForm("Edit","program","",FormMethod.Post,new {enctype = "multipart/form-data"}))
{
<div class="upload">
<input type="file" name="files" id="EpExpert"/>
<input type="file" name="files" id="EpNewbie"/>
<input type="submit" name="submit" value="submit" id="submit"/>
</div>
}
Controller:
[HttpPost]
public ActionResult Edit(tr_program program, IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file != null)
{
//string extension = Path.GetExtension(file.FileName);
string path = AppDomain.CurrentDomain.BaseDirectory + "Documents/Program-PDFs/";
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Path.Combine(path, filename));
}
}
}
uploaded file name should be in file-{id}.pdf
eg: file-EpNewbie.pdf
file-EpExpert.pdf
PLEASE help!!
The id is never sent to the server. You could use the name attribute instead:
#using (Html.BeginForm("Edit", "program", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="upload">
<input type="file" name="EpExpert" />
<input type="file" name="EpNewbie" />
<input type="submit" name="submit" value="submit" id="submit"/>
</div>
}
and in your controller action:
[HttpPost]
public ActionResult Edit(tr_program program)
{
string location = Server.MapPath("~/Documents/Program-PDFs");
foreach (string name in Request.Files)
{
HttpPostedFileBase file = Request.Files[name];
string filename = string.Format("file-{0}.pdf", name);
filename = Path.Combine(location, filename);
file.SaveAs(filename);
}
...
}
Obviously since you are storing all the files in the same location (~/Documents/Program-PDFs) with the same names (file-EpExpert.pdf and file-EpNewbie.pdf) if 2 users upload different files at the same time they might get overwritten. There seems to be a problem with your design and naming convention but in my answer I illustrated how you could pass the name of the file input to the controller action which could be used to build the resulting filename. Now it's up to you to take this into consideration when building your real application.
You can take an idea from here. Firstly declare id and data-id dynamic. for example
id = '#model.Id' data-id = '#model.Id'
Before submit form, use js or jquery take id value, then post form.
$("#myForm").submit(function () {
var idValue = $(this).attr('data-id');
document.getElementById('yourHiddenValue').value = idValue;
});