我在控制器和視圖中獲得以下代碼。問題是模型(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