Trouble uploading file ASP.NET MVC3. XML file to Model - asp.net-mvc-3

I'm attempting to upload an xml file to my site. However, regardless of which file I attempt to upload, the HttpPostedFileBase element in my code is null. I don't understand why this is. I've followed all the examples I can find on uploading files and it doesn't seem to make any sense. This is the controller method
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase xmlFile)
{
if (xmlFile != null && xmlFile.ContentLength > 0)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile.InputStream);
// other logic later
return RedirectToAction("Index");
}
return RedirectToAction("UploadFailed");
}
and the cshtml:
#{
ViewBag.Title = "Upload";
}
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}

It has a wrong name. The action argument is called xmlFile whereas your file input is called file. You need to be consistent in your naming conventions:
<input type="file" name="xmlFile" />
I also invite you to checkout Phil Haack's blog post on this subject.

Related

How to upload files in asp.net 3.1 MVC with AJAX

I'm new to asp.netcore 3.1, and now I'm learning how to upload file using AJAX in MVC, so I have tried the code that I got and here the code
in view cs.html `Upload one or more files using this form:
</p>
<input type="file" name="files" multiple />
</div></div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div></div>
</form>`
In my controller:
[HttpPost("FileUpload")]
public async Task<IActionResult> Index(List<IFormFile> files) {
long size = files.Sum(f => f.Length);
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\Files\\");
var filePaths = new List<string>();
foreach (var formFile in files) {
if (formFile.Length > 0) {
// full path to file in temp location
var filePath = Path.Combine(basePath, formFile.FileName);
filePaths.Add(filePath);
using (var stream = new FileStream(filePath, FileMode.Create)) {
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePaths });
}
I tried to change this:
asp-controller="FileUpload" asp-action="Index">
The code above was made so that the action directly goes to the directed controller, but I want to change so it would pass the file to AJAX first.

Result not showing with unobtrusive ajax in mvc 3

I'm trying to implement a little ajax using unobtrusive ajax of mvc 3. Here is the code snippet:
Controller:
[HttpGet]
public ActionResult ViewEmployee()
{
return View();
}
[HttpPost]
public ActionResult ViewEmployee(EMPLOYEE model)
{
var obj = new EmployeeService();
var result=obj.FindEmployee(model);
return View("ViewEmployee", result);
}
View:
#{AjaxOptions AjaxOpts = new AjaxOptions { UpdateTargetId = "ajax", HttpMethod = "Post" };}
#using (Ajax.BeginForm("ViewEmployee", "Home", AjaxOpts))
{
#Html.LabelFor(x => x.EmployeeID)
#Html.TextBoxFor(x => x.EmployeeID)
<input type="submit" name="Find Name" value="Find Name" />
}
<div id="ajax">
#{
if (Model != null)
{
foreach (var x in Model.EmployeeName)
{
#x
}
}
else
{
#Html.Label("No Employee is selected!")
}
}
</div>
I debugged the code, its sending the employee id to the ViewEmployee method, finding the name but not being able to display the name back into the view.
I've activated the unobtrusive ajax property in web.config & imported the scripts into the view.
Whats going wrong with this? Please help.
This is simple but effective article, ask me if you have any more question! I resolved the problem! By the way, whats wrong with stackoverflow, i'm not getting no response literally!
http://www.c-sharpcorner.com/UploadFile/specialhost/using-unobtrusive-ajax-forms-in-Asp-Net-mvc3/

ASP.Net MVC File uploading ViewModel Binding

So I'm fairly new to ASP.net MVC and have been trying to make a fileuploader, but I can't seem to get my uploaded file bound to my viewmodel. I'm trying to apply validation to the uploaded file through my viewmodel which should be doable.
My code:
View:
<div id = "PDFForm">
#using (Ajax.BeginForm("Upload", "Home", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "PDFForm",
},
new { id = "UploadForm", enctype = "multipart/form-data" }))
{
<input type="file" name="Cover" id="Cover" />
<input type="submit" value="Upload"/>
}
</div>
ViewModel:
public class UploadVM
{
[Required]
public HttpPostedFileBase Cover { get; set; }
}
Controlller action:
public ActionResult Upload(UploadVM model)
{
if(ModelState.IsValid() && model.Cover !=null)
{
//do things and return a response view
}
else
{
//return to form
}
}
I've googled around for tutorials and they seem to be able to bind the uploaded file to the viewmodel by using:
enctype = "multipart/form-data"
I can't seem to get it working so I thought you guys might be able to help me out or push me in the right direction.
Thanks in advance!
Edit: I've tried it with HTML.BeginForm() too but that doesn't seem to work either

MVC 3 Uploading File - Null File in Controller

I don't know what I'm missing, but I need to upload a file using C# MVC 3. I followed instructions here in SO, but the file is always empty.
Here is my actual testing code:
HTML
#using (Html.BeginForm("Prc", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />
}
Controller
[HttpPost]
public ActionResult Prc(HttpPostedFile file)
{
if (file != null && file.ContentLength > 0)
{
var filename = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(Server.MapPath("~/Content/Images"), filename);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
When I run the web app, I attach a file, and click Submit. But when I reach the Controller, the file object is null. Always null. I tried an XML file, a JPEG file, and a GIF file but none of them worked.
Should I configure something else besides just these codes?
Thanks
In MVC you need to use HttpPostedFileBase instead of the HttpPostedFile:
[HttpPost]
public ActionResult Prc(HttpPostedFileBase file)
{
//...
}
One more thing might trip you up.
Using asp.net mvc 3 razor, I was just surprised to discover that the name of the HttpPostedFileBase variable passed to the controller method must match the id and name of the file input tag on the the view. Otherwise asp.net passes null for the HttpPostedFileBase variable.
For example, if your file input looks like this: < input type="file" name="filex" id="filex" />
And your controller method looks like this:
public ActionResult Uploadfile(HttpPostedFileBase filey)
You'll get NULL for the "filey" variable. But rename "filey" to "filex" in your controller method and it posts the file successfully.

asp.net mvc 3 - uploading a file to server I can't save the file name to database model

What is wrong with this:
View
#model GestionWeb.DAL.Client
#using (Html.BeginForm("Index", "Config", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.LabelFor(model => model.TimeZone)
#Html.EditorFor(model => model.TimeZone)
#Html.ValidationMessageFor(model => model.TimeZone)
#Html.HiddenFor(model => model.ClientId)
#Html.LabelFor(model => model.Logo)
<input type="file" name="Logo" id="Logo" />
#Html.ValidationMessageFor(model => model.Logo)
<input type="submit" value="Upload" />
}
Controller:
[HttpPost]
public ActionResult Index(Client client)
{
if (ModelState.IsValid)
{
if (Request.Files[0].ContentLength > 0)
{
HttpPostedFileBase file = Request.Files[0];
string filePath = Path.Combine(HttpContext.Server.MapPath("/Upload/"), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
client.Logo = file.FileName;
}
db.Client.Attach(client);
UpdateModel<Client>(client);
//db.ObjectStateManager.ChangeObjectState(client, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(client);
}
I can write the file, but the file name is not saved to database, I'm not getting errors, I can update TimeZone field (and so many others).
What I'm doing wrong? I cannot figure out!!!
Thanks
You should generate a new and valid filename by yourself. It will be less error-prone for your issue. And it will avoid security issues.
For example, you can generate the filename using a string.Format():
string myGeneratedFileName = string.Format("client-logo-{0}", Guid.NewGuid());
string filePath = Path.Combine(HttpContext.Server.MapPath("/Upload/"), myGeneratedFileName);
file.SaveAs(filePath);
client.Logo = myGeneratedFileName;
And BTW, you may want to handle exceptions on file.SaveAs().
If only the name is not being saved, then perhaps you have an issue with the data model. Can you check the Logo property is mapped to a valid column? You can try to remove and re-add the table in the designer to update mapping information.
I found the problem, the client.Logo = "blabla" must be after UpdateModel method, I don't know why, because if I debug the code the client.Logo value I setted is not erased after execution of UpdateModel, like these:
[HttpPost]
public ActionResult Index(Client client)
{
if (ModelState.IsValid)
{
if (Request.Files[0].ContentLength > 0)
{
HttpPostedFileBase file = Request.Files[0];
string filePath = Path.Combine(HttpContext.Server.MapPath("/Upload/"), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
db.Client.Attach(client);
UpdateModel<Client>(client);
**client.Logo = file.FileName;**
db.SaveChanges();
return RedirectToAction("Index");
}
return View(client);
}

Resources