[英]MVC HttpPostedFileBase always null
I have this controller and what I am trying to do is to send an image to the controller as a [byte], this is my controller: 我有这个控制器,我想要做的是将图像作为[字节]发送到控制器,这是我的控制器:
[HttpPost]
public ActionResult AddEquipment(Product product, HttpPostedFileBase image)
{
if (image != null)
{
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
_db.Products.Add(product);
_db.SaveChanges();
return View();
}
and on my view: 在我看来:
@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post)) {
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Category)
@Html.ValidationMessageFor(model => model.Category)
</div>
<div>
<div>IMAGE</div>
<input type="file" name="image" />
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
but the problem is that on my controller the value for image is alway null, I cant seem to get any information on the HttpPostedFileBase 但问题是在我的控制器上,图像的值总是为空,我似乎无法获得有关HttpPostedFileBase的任何信息
You need to add the encType
with multipart/form-data. 您需要使用multipart / form-data添加encType
。
@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post, new {enctype = "multipart/form-data" })) {
You can always add it to your model too as follows, providing it is a ViewModel: 您可以将其添加到模型中,如下所示,前提是它是ViewModel:
public class Product
{
public Product()
{
Files = new List<HttpPostedFileBase>();
}
public List<HttpPostedFileBase> Files { get; set; }
// Rest of model details
}
You can the retrieve the files by removing the un-needed parameter ie 您可以通过删除不需要的参数来检索文件,即
[HttpPost]
public ActionResult AddEquipment(Product product)
{
var file = model.Files[0];
...
}
Try to do this at the top of the Action method: 尝试在Action方法的顶部执行此操作:
[HttpPost]
public ActionResult AddEquipment(Product product, HttpPostedFileBase image)
{
image = image ?? Request.Files["image"];
// the rest of your code
}
And the form should have enctype of "multipart/form-data" to upload files: 表单应该有“multipart / form-data”的上传类型来上传文件:
@using (Html.BeginForm("AddEquipment", "Equipment", FormMethod.Post, new {enctype = "multipart/form-data" })) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.