我试图在我的数据库中存储一个类别对象并上传一个我可以参考这个类别的图像,
该类别已完美存储,但由于某种原因未上传图像。当我调试时,我可以看到我的应用程序永远不会进入将文件存储在服务器上的方法,因为我的文件是“Null”。
模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace SkyLearn.Areas.Categories.Models
{
public class Category
{
public int ID { get; set; }
public string Title { get; set; }
public string Icon { get; set; }
public string Description { get; set; }
}
public class CategoryDBContext : DbContext
{
public DbSet<Category> categories { get; set; }
}
}
控制器:
//
// POST: /Categories/Category/Create
[Authorize(Roles = "administrator")]
[HttpPost]
public ActionResult Create(Category category, HttpPostedFileBase Icon)
{
if (Icon != null && Icon.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(Icon.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("../Content/icons/"), fileName);
Icon.SaveAs(path);
category.Icon = fileName;
}
if (ModelState.IsValid)
{
db.categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
看法:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.master" Inherits="System.Web.Mvc.ViewPage<SkyLearn.Areas.Categories.Models.Category>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
<% using (Html.BeginForm()) { %>
<form action="" method="post" enctype="multipart/form-data">
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Category</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.Title) %>
<%: Html.ValidationMessageFor(model => model.Title) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Icon) %>
</div>
<div class="editor-field">
<input type="file" name="icon" id="icon"/>
</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>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</form>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
谁能告诉我为什么它不会进入保存文件ID的方法,不胜感激。
我尝试在stackoverflow上查看其他答案,即使其中一些与我有同样的问题,但他们的解决方案并没有解决我的问题。
我还尝试在我的 config.web 中更改上传大小等。
请帮我 :)