我在控制器和视图中获得以下代码。问题是模型(Photo是一个实体框架实体)是空的(所有字段都是空的)。为什么?提交asp.net mvc 2表格时的空模型
// GET: /Admin/Photo/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Admin/Photo/Create
[HttpPost]
public ActionResult Create(int id, FormCollection collection)
{
try
{
var file = (HttpPostedFileBase) Request.Files[0];
if (file != null && file.FileName != null)
{
var filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Photos/Product/", Path.GetFileName(file.FileName));
file.SaveAs(filename);
var photo = new Photo();
photo.Description = collection["Description"];
photo.Main = collection["Main"].Contains("true");
photo.Filename = Path.GetFileName(file.FileName);
photo.Product_Id = id;
Entities.AddToPhotos(photo);
Entities.SaveChanges();
}
else
{
ModelState.AddModelError("", "Plik musi zostać załadowany.");
return View();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
<h2>Create</h2>
<% using (Html.BeginForm(null, null, null, FormMethod.Post, new {enctype = "multipart/form-data" })) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Description) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Description) %>
<%: Html.ValidationMessageFor(model => model.Description) %>
</div>
<div class="editor-label">
<label for="MainContent_file">Plik: </label>
</div>
<div class="editor-field">
<asp:FileUpload ID="file" runat="server" />
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Main) %>
</div>
<div class="editor-field">
<%: Html.CheckBoxFor(model => model.Main) %>
<%: Html.ValidationMessageFor(model => model.Main) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
更新:我检查和收集填充了适当的领域,但它们都清零。
只是一个单纯的拷贝,并与您的代码和HTML粘贴 - 用只包含描述及主要的模型 - 它工作得很好。该问题可能存在于此特定文件之外。您正在使用asp:FileUpload控件。尝试用输入替换它。但是,您必须删除主页面中的
没有FileUpload控件,它工作得很好。我不必删除masterpage中的
嗯,我问的表单标签的原因是因为一个新的项目与asp:FileUpload标签抛出一个错误,它需要与runat =服务器的表单标签...所以基于该表单标签肯定存在,在某处。 – Buildstarted 2010-09-24 19:26:14