I have this kind of problem: In a view I have one button upload which uploads an image and stores it to some folder. Is there a way to call action upload, but not to return a view? Just to save that content, and then I have another button next which will redirect me to a new view. I tried with return type void, but it sends me to blank page.
This are form buttons for upload and next
#using (Html.BeginForm("Upload", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(model => model.Picture, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<span class="btn btn-primary btn-file">
Choose <input type="file" name="file" />
</span>
<input type="submit" value="Upload" name="buttonName" class="btn btn-primary"/>
</div>
</div>
}
#using (Html.BeginForm("Next", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Next" name="buttonName" class="btn btn-default" />
</div>
</div>
}
This is action:
public void Upload(HttpPostedFileBase file, string btnSubmit)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
You can use the Content() method to return ContentResult ContentResult by default returns a text/plain as its contentType.
public ActionResult Upload(HttpPostedFileBase file, string btnSubmit)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
return Content("Success");
}
You could return an EmptyResult.
MVC wants you to use EmptyResult when the action is specifically
intended to return nothing. Unlike all of the previous ActionResults
though, EmptyResult doesn't have a helper. Additionally, if an action
returns null, MVC will detect that and make it return an EmptyResult.
Ok, I searched about this and I think that i need some ajax without refreshing page. I found this File upload using MVC 4 with Ajax. I'll try it to see if this works.
The correct solutions are to use either:
return new HttpStatusCodeResult(HttpStatusCode.OK);
to indicate the upload was received and all processing has completed.
return new HttpStatusCodeResult(HttpStatusCode.Accepted);
to indicate the upload was received and further processing will continue.
Related
I'm currently working on a project where I upload files with the following code:
<div class="row">
<div class="col-lg-2 d-flex align-items-stretch">
#using (Html.BeginForm("ImportOther", "Mapper", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<label class="btn btn-block btn-primary">
Other JSON / XML <input type="file" name="jsonFileOther" onchange="this.form.submit()" style="display: none;">
</label>
</p>
}
</div>
</div>
How can I show a succes alert when file has been uploaded? I've used alerts in javascript so far. Hope anyone has some suggestions.
Thanks in advance!
After you have submitted your form to the Controller, based upon your upload result, you can set a message using ViewBag.
In your Controller:
if(fileUpload == true)
{
ViewBag.UploadMessage = "File Successfully Uploaded";
}
else
{
ViewBag.UploadMessage = "Could Not Upload File";
}
You can use the ViewBag like this in your View:
#if(ViewBag.UploadMessage != null)
{
<script>
$(document).ready(function(){
alert('#ViewBag.UploadMessage ');
});
</script>
}
Note: Instead of using return RedirectToAction(), use return View() to preserve your ViewBag variable.
Let's assume I have a simple page with some information and a form.
#using (Html.BeginForm("UpdateOrder", "OrderController", FormMethod.Post)) {
// some inputs here
}
<p id="user_info">Some text here</p>
All input's data will be sent like model or by FormCollection to the Controller.
However, I want also to send to the controller any text\image, generally any information from the page that located outside the form. Here text with id "user_info" as an example.
I wonder if it could be implemented without jQuery, only by using default Controller's functionality.
You can do it simply
1- if you want to upload some documents or images than your form should be like
bellow code:
#using (Html.BeginForm("ApplyOnline", "Applieds", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="hidden" name="JobId" id="JobId" value="#ViewBag.JobId" />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-3">First Name (اسم)</label>
<div class="col-md-8">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control",#required="required" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<input type='file' name='pmd' id='pmd' />
<input type="submit" value="Apply" class="btn btn-primary" />
}
than in countroller in post method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ApplyOnline([Bind(Include = "Id,JobId,FirstName")] Applied applied, HttpPostedFileBase pmd, int JobId)
{
if (ModelState.IsValid)
{
//---save the data---------//
db.MyAppliedContext.Add(applied);
db.SaveChanges();
//---Get inserted Id----//
int insertedId = applied.Id;
//--------Upload PMD-------------------//
if (pmd != null && pmd.ContentLength > 0)
{
try
{
var PMDFileName = "PMD-" + applied.JobId + "-" + TrimedUser + "-" + insertedId + "-" + pmd.FileName;
//var P11FileName = DateTime.Now.ToString();
string path = Path.Combine(Server.MapPath("~/App_Data/system"),
Path.GetFileName(PMDFileName));
pmd.SaveAs(path);
UploadFiles MyPMDUploads = new UploadFiles();
MyPMDUploads.JobId = applied.JobId;
MyPMDUploads.ApplyId = insertedId;
MyPMDUploads.FileName = Path.GetFileName(PMDFileName);
MyPMDUploads.FilePath = path;
db.MyUploadFileContext.Add(MyPMDUploads);
db.SaveChanges();
ViewBag.Message = "PMD uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR PMD:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "You have not specified a PMD file.";
}
}
return view(Model);
}
this way you can upload files and data all is included hop this help you
Try using hidden field to send additional data form to controller.
#using (Html.BeginForm("UpdateOrder", "Order", FormMethod.Post)) {
// some inputs here
<input type="hidden" name="user_info" id="user_info" value="Norway">
}
//<p id="user_info">Some text here</p>
and in OrderController controller action method
public ActionResult UpdateOrder(String user_info)
{
//Hidden filed **name** will be the name of the String
//From collection can be used in similar way
}
EDIT: you can update hidden field value by jQuery/javascript and after submission you can get updated value in controller and text/image it is slightly different
I have a MVC 5 controller with views, using Entity Framework project.
I have a controller and view for my Item Model:
public partial class Item
{
public int ItemID { get; set; }
public string ImageURL { get; set; }
}
I changed the Entity Framework Create view and controller to post an html file input and save the file path as the ImageURL
A snippet from the view looks like this:
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<fieldset>
<legend>Upload a file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
The controller's Create ActionResult looks like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ItemID,ImageURL")] Item item, HttpPostedFileBase file)
{
try
{
if (ModelState.IsValid && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
file.SaveAs(path);
item.ImageURL = "/Uploads/" + file.FileName;
db.Items.Add(item);
db.SaveChanges();
}
ViewBag.Message = "Upload successful";
return RedirectToAction("Index");
}
catch
{
ViewBag.Message = "Upload failed";
ViewBag.ItemTypeID = new SelectList(db.ItemTypes, "ItemTypeID", "ItemType1", item.ItemTypeID);
return View(item);
}
}
As you can see I use var fileName = Path.GetFileName(file.FileName); and item.ImageURL = "/Uploads/" + file.FileName; To populate my ImageUrl. The file itself is saved on the server.
Now my issue is that I don't know how to get the "Edit" view and ActionResult to allow me either to keep the same image or upload a new image.
How can I do this?
What I have done so far is in the Edit view to write:
<div class="form-group">
#if (Model.ImageURL == null)
{
<fieldset>
<legend>Upload a file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
}
else
{
/*Keep or upload new image here*/
}
</div>
What would I need to write in that else {...} and what would I need to write in the controller's public ActionResult Edit(int? id) {...} ?
Just show Image in the img control and below that use another file control , in case user need to change the uploaded image..
<div class="form-group">
#if (Model.ImageURL == null)
{
<fieldset>
<legend>Upload a file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
}
else
{
/*show Image in an img control using image path*/
<img src="#Model.ImageURL" height="100" width="100" />
<fieldset>
<legend>change the file</legend>
<div class="editor-field">
#Html.TextBox("file", "", new { type = "file" })
</div>
</fieldset>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
and at Action part everything will be same , remove the old file and save new one and update db as well.
also Don't forget to use form as you have used in the create view.
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
if image is not uploaded For the particular item How you will edit . You can do create and edit both in single action method by
var itemInDb = db.items
.Where(c => c.itemid== id) // or whatever your key is
.SingleOrDefault();
if (itemInDb != null)
db.Countries.ApplyCurrentValues(item);
else
db.Countries.AddObject(item);
db.SaveChanges();
if multiple images are there for single image you can loop it
I have a problem when i try to upload a file in ASP.NET MVC5.
Somehow "HttpPostedFileBase file" always returns null, i can't find my problem.
My Code:
(Controller)
public ActionResult Edit(PMNieuwePloeg ploeg, FormCollection frm, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("/Content/ImagesPloegen/"), fileName);
file.SaveAs(path);
ploeg.NieuwPloeg.ImageUrl = file.FileName;
}
else
{
ploeg.NieuwPloeg.ImageUrl = "/geen.jpg";
}
if(ploeg.NieuwPloeg.LandID > 0)
{
ploeg.NieuwPloeg.UserId = UserManager.FindByName(User.Identity.Name).Id;
ploeg.NieuwPloeg.UserName = UserManager.FindByName(User.Identity.Name).UserName;
repoPloegen.Edit(ploeg.NieuwPloeg);
}
return RedirectToAction("Index");
}
View
#using (Html.BeginForm("Edit","Ploegen", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Ploeg</h4>
<div class="form-group">
#Html.LabelFor(model => model.NieuwPloeg.ImageUrl, "Ploeg Image", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="file" required />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Can anyone on here spot the problem?
in Controller
HttpPostedFileBase casteCertificate = Request.Files["UploadRegCard"];
in view
#using (Html.BeginForm("ActionMethod", "Controller", FormMethod.Post, new { enctype = "multipart/form-data", name = "myForm", id = "myForm" }))
{
<input type="file" name="UploadRegCard" id="UploadRegCard" class="form-control" />
}
using name attribute of input element you can retrive file from view to controller
Check Request.Files array in controller. It should contain all your posted files from client
I am attempting to pass a IList of HttpPostedFileBase objects and a "Post" object to an Action. I receive the Post object just fine but my IList is always empty.
See code below...
Controller Action:
[HttpPost]
public ActionResult Create(Post post, IList<HttpPostedFileBase> attachments)
{
if (ModelState.IsValid)
{
var attachmentCounter = attachments.Count;
post.SubmissionDateTime = DateTime.Now;
db.Posts.AddObject(post);
db.SaveChanges();
return RedirectToAction("Index", new { category = post.Category });
}
return View(post);
}
View:
#using (Html.BeginForm("Create", "Posts", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Post</legend>
#Html.HiddenFor(model => model.Category)
#Html.HiddenFor(model => model.Author)
<div class="editor-label">
<label>Photo Attachments:
<span style="color:#666; font-size:12px; font-weight:normal;">(Optional)</span>
</label>
</div>
<div class="editor-field">
#Html.Raw(FileUpload.GetHtml(
name: "attachments",
initialNumberOfFiles: 1,
allowMoreFilesToBeAdded: true,
includeFormTag: false,
addText: "Add another photo...",
uploadText: "").ToString().Replace("<input value\"\" type=\"submit\" />", ""))
</div>
<br />
<p>
<input type="submit" value="Create" class="createButton" style="font-weight:normal;" /> |
#Html.ActionLink("Back to List", "Index", null, new { category = Model.Category }, null)
</p>
</fieldset>
}
I was trying to reproduce your issue, but in my environment all is working. But anyway check once again that your name property in FileUpload exactly the same as second parameter property in controller (even better copypaste it). The Second thing you need to check is the size of file you uploading to the server. If it's bigger then request size allowed in your web config, values will be null.
Also you could check in your method value of Request.Files if it's empty that will means that your file do not even uploading to server. If file will be available, you could get it from there.