Image upload using #Ajax.BeginForm in .NET MVC? - asp.net-mvc

I want to upload image using Ajax.BeginForm in my application.
Currently HttpPostedFileBase file is getting value 0. Anyone Please guide me here.
I have tried this code but file is not uploading.
Appreciated, if anyone can provide some solutions for this. If I use #Html.BeginForm then It works but I want to use #Ajax.BeginForm.
Model
public class ClsUpload
{
public string FilePath { get; set; }
}
Controller
public ActionResult Edit(ClsUpload model,HttpPostedFileBase file)
{
if (Request.Files.Count > 0)
{
file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("/Content/Images/"), fileName);
file.SaveAs(path);
model.FilePath = path;
}
}
try
{
UploadDetials details = new UploadDetials();
details.UpdateDetails(model);
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Index");
}
}
Partial View
#model XX.X.Models.File.ClsUpload
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "partial", InsertionMode = InsertionMode.Replace }))
{
#Html.HiddenFor(model => model.FilePath)
<input type="file" name="file" />
<img src=#Model.FilePath alt="Image" />
<input type="submit" value="Save" />
}

You can update your code with FormMethod.Post, new { enctype = "multipart/form-data" }) and [AcceptVerbs(HttpVerbs.Post)] as follow
In Partial View
#using (Html.BeginForm("ActionMethod1", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
In Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ActionMethod1(HttpPostedFileBase pic)
{
}

This is old, but I want to show how I have accomplished uploading a file using Ajax.BeginForm(). Basically, the overloads will tell you what is possible. I use the overload for: "string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes". Note: I use null for "routeValues".
Here is a code example:
#using (Ajax.BeginForm("UploadFile", "Home", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "MyIDToUpdate", OnSuccess = "EditSuccessClearForm('IDToClear', '')", OnFailure = String.Format("NewGenericFailure(xhr, '{0}')", "#IDToPassThisFunction"), InsertionMode = InsertionMode.ReplaceWith }, new { enctype = "multipart/form-data", #id = "NewFileFormID" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-8 col-sm-offset-1">
#Html.TextBox("file", "", new { type = "file", accept = ".jpg, .jpeg, .png, .pdf", #id = fileID, onchange = VerifySizeOfFile })
</div>
<div class="col-sm-2">
<button type="submit" id="FileSubmitButton" class="btn btn-primary">Upload</button>
</div>
</div>
}

Related

Request.Files.Count always 0 when using an input of type file

I am not able to get the uploaded file, it always shows Request.Files.Count as 0.
#using (Html.BeginForm("HandleForm", "Home", new { EncType = "multipart/form-data" }))
{
<div>Upload Something:
<input type="file" name="uploadedFile" />
</div>
<br/>
<input type="submit" value="Submit" />
}
Controller Action:
public ActionResult HandleForm(HttpPostedFileBase uploadedFile)
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
return View("FormResults");
}
You are using the wrong overload of BeginForm() and adding a route value for enctype, not a html attribute.
You need to use this overload
#using (Html.BeginForm("HandleForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))`

File upload not working as expected

I am trying to upload a file from my application and it is not working as expected. I am not getting any file into the action method.
I have my viewmodel as below
public class CallQueryViewModel
{
[Display(Name = "Attachment")]
public HttpPostedFileBase UploadFile { get; set; }
}
And my Razor form is as below
#{
var ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "onCallAddBegin",
OnSuccess = "OnCallCreateSuccess",
OnFailure = "OnCallCreateFailure"
};
}
#using (Ajax.BeginForm("AddCall", "CallHandling", ajaxOptions, new { #id = "CallAddForm", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.UploadFile, new { #class = "col-md-2" })
#Html.TextBoxFor(model => model.UploadFile, new { #class = "col-md-10", type="file" })
</div>
</div>
</div>
<div id="Submit">
<input type="submit" value="Save" class="btn btn-success" />
</div>
}
And my controller action method is as below.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddCall(CallQueryViewModel model)
{
if ((model.UploadFile != null) && (model.UploadFile.ContentLength > 0))
{
// Upload file.
}
}
With the above code, when i am trying to upload the file, I am not receiving any file into the controller action method. The UploadFile is always coming as null.
Could someone suggest what I am missing ?

File uploading in MVC 4

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"

How to display a model state error in case I am returning a partial view

I have the following action method for creating new network info:-
public ActionResult CreateVMNetwork(int vmid)
{
VMAssignIps vmips = new VMAssignIps()
{
TechnologyIP = new TechnologyIP() { TechnologyID = vmid},
IsTMSIPUnique = true,
IsTMSMACUnique = true
};
return PartialView("_CreateVMNetwork",vmips);
}
[HttpPost]
public ActionResult CreateVMNetwork(VMAssignIps vmip)
{
if (ModelState.IsValid)
{
try
{
repository.InsertOrUpdateVMIPs(vmip.TechnologyIP,User.Identity.Name);
repository.Save();
return PartialView("_networkrow",vmip);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error occurred: " + ex.InnerException.Message);
}
}
return PartialView("_CreateVMNetwork", vmip);
}
And I have the following _CreateVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
#using (Ajax.BeginForm("CreateVMNetwork", "VirtualMachine", new AjaxOptions
{
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "networktable",
LoadingElementId = "loadingimag",
HttpMethod= "POST"
}))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model=>model.TechnologyIP.TechnologyID)
#Html.Partial("_CreateOrEditVMNetwork", Model)
<input type="submit" value="Save" class="btn btn-primary"/>
}
and _CreateOrEditVMNetwork view:-
#model TMS.ViewModels.VMAssignIps
<div>
<span class="f">IP Address</span>
#Html.EditorFor(model => model.TechnologyIP.IPAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.IPAddress)
<input type="CheckBox" name="IsTMSIPUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) /> |
<span class="f"> MAC Address</span>
#Html.EditorFor(model => model.TechnologyIP.MACAddress)
#Html.ValidationMessageFor(model => model.TechnologyIP.MACAddress)
<input type="CheckBox" name="IsTMSMACUnique" value="true" #(Html.Raw(Model.IsTMSMACUnique ? "checked=\"checked\"" : "")) />
</div>
The problem I am facing is that in case there is a model state error when adding a new entity, a partial view will be displayed with the model state error as follow:-
So my question is , if there is a way to display the model state error with the partial view , without updating the table row “insert after” as I am doing currently?
Thanks
Given the age i'm guessing you have already found a solution to this,
But here is an example using InsertionMode.Replace, maybe it can help someone else.
Snipped from view
#using (Ajax.BeginForm("AddPerson", "Home", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "UpdateSection" }))
{
<div id="UpdateSection">
#Html.Partial("PersonModel", Model.Person)
</div>
<input type="submit" value="add" />
}
Snipped from the controller
if (!ModelState.IsValid)
{
return PartialView("AddPerson", Person);
}
just make sure the "jquery.unobtrusive-ajax.min.js" script is included (i'm not sure it is by default)

multiple image uploads in mvc3

If I have situation like below, where I success. handle image upload and store in db. Having this code in mind how would you implement multiple image upload.
Thank you.
So first thing first.
PropertyViewModel.cs
...
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public PropertyViewModel(Property x)
{
....
ImageData = x.ImageData;
ImageMimeType = x.ImageMimeType;
}
public void ToDomainModel(Property x)
{
....
x.ImageData = ImageData;
x.ImageMimeType = ImageMimeType;
}
Now form Create.cshtml razor page
#using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image"/>
}
}
Controller to handle request
[HttpPost]
public ActionResult Create(PropertyViewModel newProperty, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null)
{
newProperty.ImageMimeType = image.ContentType;
newProperty.ImageData = new byte[image.ContentLength];
image.InputStream.Read(newProperty.ImageData, 0, image.ContentLength);
}
using (session...)
{
using (...begin transaction)
{
MyDomain.Property model = new MyDomain.Property();
newProperty.ToDomainModel(model);
..session save model
.. commiting session
}
}
return RedirectToAction("Index");
}
else
{
return View(newProperty);
}
}
#using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image"/>
<input type="file" name="Image"/>
<input type="file" name="Image"/>
<input type="file" name="Image"/>
}
or if the browser supports HTML5 you could select multiple files in the upload dialog:
#using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image" multiple="multiple"/>
}
and then:
public ActionResult Create(PropertyViewModel newProperty, IEnumerable<HttpPostedFileBase> image)

Resources