C# .NET MVC3图像上载相关错误:从类型转换为';System.Web.HttpPostedFileWrapper';输入';Project.Domain.Entities.Image';
我会尽量简单地解释: 我有一个实体-图像-如下所示:C# .NET MVC3图像上载相关错误:从类型转换为';System.Web.HttpPostedFileWrapper';输入';Project.Domain.Entities.Image';,c#,.net,image,upload,type-conversion,C#,.net,Image,Upload,Type Conversion,我会尽量简单地解释: 我有一个实体-图像-如下所示: public class Image : IEntity { public int ID { get; set; } public string name { get; set; } public virtual ICollect
public class Image : IEntity
{
public int ID
{
get;
set;
}
public string name
{
get;
set;
}
public virtual ICollection<Restaurant> Restaurant
{
get;
set;
}
}
}
在我看来,用户拍摄图像并上传以保存给他们的用户,我有一个简单的
,带有enctype=“multipart/form data”。本例中的用户是实体-餐厅
@using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
[...]
<input type="file" name="image" />
[...]
运行代码时,ModelState.IsValid()返回false,ModelState错误如下:
{System.InvalidOperationException:从类型'System.Web.HttpPostedFileWrapper'到类型'Projct.Domain.Entities.Image'的参数转换失败,因为没有类型转换器可以在这些类型之间转换
有什么想法吗?modelbinder尝试绑定
,看看这里如何使用MVC上传图像
@using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
[...]
<input type="file" name="image" />
[...]
[HttpPost]
public ActionResult Edit(Restaurant rest, Address address, HttpPostedFileWrapper image)
{
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var filename = Path.GetFileName(image.FileName);
Guid imageID = Guid.NewGuid();
var relativePath = @"~/Content/Images/Logotypes/" + imageID.ToString();
image.SaveAs(Server.MapPath(relativePath));
rest.ImageMimeType = image.ContentType;
rest.ImageName = filename;
rest.ImageID = imageID;
repo.Save(rest);
}
return View(rest);
}
else
{
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
return View(rest);
}
}