Reputation: 1088
I have problem with uploading image to SQL database. i have Methods Upload in controller Upload
dbData userDb = new dbData();
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileWrapper file)
{
if (file.ContentLength > 0)
{
Stream fileStream = file.InputStream;
string fileName = Path.GetFileName(file.FileName);
int fileLength = file.ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
var image = new ImageTable();
image.Image = fileData;
image.Description = "Default profile picture";
try
{
userDb.ImageTables.InsertOnSubmit(image);
userDb.SubmitChanges();
return RedirectToAction("Success");
}
catch (Exception ex)
{
throw;
}
}
return View();
}
If i use this view page
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Upload</title>
</head>
<body>
<div>
<% using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input name="file" type="file" runat="server" id="file"/><br />
<input type="submit" value="Upload File" />
<%} %>
</div>
</body>
</html>
everithing works great but if i want to use view runned on masterpage i wil get this error after i click upload submit button:
No parameterless constructor defined for this object.
Know someone where is problem and how can i fix it ? Thanks
Upvotes: 1
Views: 748
Reputation: 3034
This error occurs because default model binder can't create instances of classes that don't contain parameterless constructor (such as HttpPostedFileWrapper
).
Simplest way around this is to just pull files from Request.Files
(e.g. Request.Files["file"]
).
Alternatively, you could create custom model binder for that.
UPDATE:
This is action method I used:
[HttpPost]
public ActionResult Index(FormCollection form)
{
var file = Request.Files["file"];
if(file != null && file.ContentLength > 0)
{
// ...
}
return View();
}
Upvotes: 1