MVC 4 HttpPostedFileBase always null - asp.net-mvc

No matter what I try my post images are always null or Object reference not set to an instance of an object.
I have a post class and images class that map to tables (Using EF code first)
Here's my code:
View:
<h2>Create</h2>
#using (Html.BeginForm("Create", "Admin", FormMethod.Post, new{ enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
#Html.LabelFor(post => post.Post.Blog)
#Html.DropDownListFor(post => post.Post.BlogId, Model.BlogList)
#Html.LabelFor(post => post.Post.Category)
#Html.DropDownListFor(post => post.Post.CategoryId, Model.CategoryList)
#Html.LabelFor(post => post.Post.Title)
#Html.EditorFor(post => post.Post.Title)
<br />
#Html.LabelFor(post => post.Post.Content)
#Html.EditorFor(post => post.Post.Content)
<br />
<input type="file" name="uploadImage" value="Upload" />
<input type="submit" value="Create" />
}
Action Method:
[HttpPost]
public ActionResult Create(Post post, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
var postBlog = _repository.Blogs.Single(b => b.BlogId == post.BlogId);
post.Created = DateTime.Now;
postBlog.Posts.Add(post);
PostImage newImage = new PostImage()
{
MimeType = image.ContentType,
ImageData = new byte[image.ContentLength],
PostId = post.PostId
};
_repository.AddImage(newImage);
_repository.Save();
return RedirectToAction("Index");
}

Doh! the problem was I had set 'value' in the input element you only need input type="file" name="Image" /> for it to bind correctly

Related

Multiple Action of Controller in single Button in MVC 4

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

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)

how do i refere my textbox of type file from view to controller

Im trying to upload an image to the database but i im getting an error with object refernece not set to an instance of an object.
i have a textbox in the view and im using memorystream in the controller but i cant store the image to the memorystream.
i also have a model where have this property
public HttpPostedFileBase file { get; set; }
heres the code from the view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Picture</legend>
#Html.TextBoxFor(m => m.file, new { type = "file" })
#*<input type="file" value="file" />*#
<input type="submit" value="Create" />
</fieldset>
}
and this is the code from the controller:
[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
var memoryStream = new System.IO.MemoryStream();
file.InputStream.CopyTo(memoryStream);
var fileBytes = memoryStream.ToArray();
return RedirectToAction("Index");
}
add enctype attribute your form element
#using (Html.BeginForm("Create",
"Home",
FormMethod.Post,
new { id = "form", enctype="multipart/form-data" }))
{
}

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