Uploading a file will pass a null object - asp.net-mvc

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?

Related

upload image from view to controller mvc

Good day,
I am trying to upload an image from my view
#using (Html.BeginForm("CrearCurso", "ProfesorCurso", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<label>Upload Image</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" id="imgInp">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<img id='img-upload'/>
</div>
}
I have this controller in mvc
[HttpPost]
public ActionResult CrearCurso(CursoViewModel CursoViewModel, HttpPostedFileBase imgInp)
{
return View();
}
However when I inspect the HttpPsotedFileBase, it is empty. What is wrong here? thanks
Forms posts back the name/value pairs of its successful form controls. Your file input has no name attribute. Change it to
<input type="file" name="imgInp">
However, its better to strongly bind to your model, so add a
public HttpPostedFileBase ImgInp { get; set; }
property to your view model and use
#Html.TextBoxFor(m => m.ImgInp, new { type = "file" })
which will also allow you to add validation attributes to your file input if required

Send Forms issue

I'm developing an application on asp.net.I use the standard modelbinder
I have code
#model Sciencecom.Models.Billboards1
#{
ViewBag.Title = "CreateBilboard";
SelectList owners = new SelectList(new SciencecomEntities().Owners.Select(m=>m.Name).ToList());
}
#using (Html.BeginForm("Bilboard", "Data", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
#Html.ValidationMessage("Error")
#*владелец*#
<input type="text" name="Locality" value="345"/>
<input type="text" name="Locality" value="3435" />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Добавить" class="btn btn-default" />
</div>
</div>
</div>
}
I send form on controller.but i have issue .I have reference-null
public ActionResult Bilboard( IEnumerable<Sciencecom.Models.Billboards1> Billboard, IEnumerable<Sciencecom.Models.Surface> test)
{
return View();
}
what ideas?
Inside your form you have only 2 input fields with the same name (Locality) which is quite confusing. So on your server all you can get is a variable with the same name as your input field because that's the only information that is posted back when the form is submitted:
public ActionResult Bilboard(Locality locality)
{
...
}
In the code you have shown in your question your Bilboard action seem to be taking some Billboard and test collection arguments but they are not present as input fields inside your form so you cannot possibly expect them to be populated.

How to pass other form data along with MVC File Upload?

I am trying to implement File Upload in MVC. I have the following code which works.
#using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
Now I want to add a dropdown box (to select the file type) and send that value along with the file to my Controller. How can I do that (send other form data along with the file)?
You should be able to add them to the view, include them in the POST and have MVC take care of the model binding:
#using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="file" />
<select name="fileType">
<option value="JPG">Photo</option>
<option value="DOC">Word</option>
</select>
<input type="submit" value="OK" class="button" />
</div>
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file, string fileType)
{
//Validate the fileType
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
//do something here...
}
}
I ended up doing it as follows it as follows. works good for me:
Created a Model:
public class FeeUpload
{
[Required (ErrorMessage="File Type required")]
public string fileType { get; set; }
[Required (ErrorMessage="file required")]
public HttpPostedFileBase File { get; set; }
}
View:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(false, "Please fix the following:")
<div>
<div>
#Html.DropDownListFor(model => model.fileType,
new List<SelectListItem>
{
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" },
new SelectListItem{ Text="xxx", Value = "yyy" }
}, "Select")
#*#Html.ValidationMessageFor(model => model.fileType)*#
</div>
<div>
#Html.TextBoxFor(model => model.File, new { type = "file" })
#*#Html.ValidationMessageFor(model => model.File)*#
<input type="submit" value="OK" class="button" id="btnsubmit" />
</div>
</div>
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FeesAndCostsUpload(FeeUpload feeUploadFile)
{
if (ModelState.IsValid)
{
//do something with feeUploadFile.File and feeUploadFile.fileType
}
return View();
}
Try to not use Razor for the form
<form method="POST" data-url="#Url.Action("Action", "Controller")" enctype="multipart/form-data">
#Html.ValidationSummary(true)
<span class="btn btn-success fileinput-button">
<i class="fa fa-plus"></i>
<span>Add a file...</span>
#Html.TextBoxFor(model => model.Fichier, new { type = "file" })
</span>
<div class="form-group form-actions">
<div class="col-sm-offset-3 col-sm-9">
<input id="submit" type="submit" class="btn btn-primary" value='Value' />
</div>
</div>
</form>
worked for me

Having trouble with ASP.NET MVC 4 image uploading

I'm trying to upload a image along with other fields. Been following examples from here and here
However it seems that the image object isn't passed to the controller and i'm unable to find any error.
Here's the view:
#model Project.Models.ContentNode
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>News</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
#*Image upload field*#
<div class="editor-field">
<input type="file" name="file" />
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Body)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Body)
#Html.ValidationMessageFor(model => model.Body)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Here are the controller methods:
public ActionResult Create()
{
var model = new ContentNode();
return View( model );
}
[HttpPost]
public ActionResult Create(ContentNode nyF, HttpPostedFileBase imageData)
{
// Get the type of content from DB
var k = (from ct in _db.ContentTypes
where ct.ID == 1
select ct).Single();
var curUser = (from u in _db.Users
where u.Username == User.Identity.Name
select u).Single();
nyF.Author = curUser;
nyF.ContentType = k;
nyF.dateCreated = DateTime.Now;
_db.ContentNodes.Add(nyF);
_db.SaveChanges();
// Process image
if ((imageData != null && imageData.ContentLength > 0))
{
var fileName = Path.GetFileName(imageData.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
imageData.SaveAs(path);
}
else
{
return Content("The image object wasn't received");
}
return View(nyF);
}
I've read over the whole thing over and over and am unable to see the error. Anyone here willing to point out what I'm doing wrong?
The name of the input file needs to match the action parameter
<input type="file" name="file" />
should be
<input type="file" name="imageData" />
or you change your action parameter name
public ActionResult Create(ContentNode nyF, HttpPostedFileBase file)
You can upload file, using Request.Files in your post method.
You can validate uploaded file using following code.
Request.Files[0].ContentLength

MVC 3 input file always null

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" />

Resources