I am using ng-upload and ASP MVC and my input saves multiple files. The files are successfully saving in the folder path specified in the controller but the file info (id, name, path and recipeId) is not saving to db.
After the controller process it returns null
to the view.
File.cs
public class File
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Name")]
[StringLength(30, ErrorMessage = "Name cannot be longer than 30 characters.")]
public string Name { get; set; }
[Display(Name = "Path")]
[StringLength(100, ErrorMessage = "Path cannot be longer than 30 characters.")]
public string Path { get; set; }
[ForeignKey("Recipe")]
public int RecipeId { get; set; }
public virtual Recipe Recipe { get; set; }
}
Angular
$scope.SelectedFiles = files;
if ($scope.SelectedFiles && $scope.SelectedFiles.length) {
Upload.upload({
url: '/Files/Upload/',
data: {
files: $scope.SelectedFiles,
RecipeId: $scope.recipeID
}
}).then(function (response) {
$timeout(function () {
$scope.Result = response.data;
});
}, function (response) {
if (response.status > 0) {
var errorMsg = response.status + ': ' + response.data;
alert(errorMsg);
} else {
console.log(response.data);
}
}, function (evt) {
$scope.Progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
Controller
[HttpPost]
public ContentResult Upload(File vm)
{
string path = Server.MapPath("~/Uploads/");
int RecipeId = vm.RecipeId;
foreach (string key in Request.Files)
{
HttpPostedFileBase postedFile = Request.Files[key];
postedFile.SaveAs(path + postedFile.FileName);
File recipefile = new File();
recipefile.Name = postedFile.FileName;
recipefile.Path = path;
recipefile.RecipeId = RecipeId;
db.Files.Add(recipefile);
}
db.SaveChanges();
return Content("Success");
}
I get the following error.
System.Data.Entity.Validation.DbEntityValidationException was unhandled by user code
HResult=-2146232032
Message=Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source=FAC Recipes
StackTrace:
at FACRecipes.Controllers.FilesController.Upload(File vm) in ...Controllers\FilesController.cs:line 52
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
InnerException:
I removed the async Task
and await db.SaveChangesAsync();
so I keep getting the validation error. The problem was that I set the StringLength
to 30
in File.cs
so I increased the StringLength
and it worked! Thanks Everyone!
public class File
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Display(Name = "Name")]
[StringLength(500)
public string Name { get; set; }
[Display(Name = "Path")]
[StringLength(100)]
public string Path { get; set; }
[ForeignKey("Recipe")]
public int RecipeId { get; set; }
public virtual Recipe Recipe { get; set; }
}