2012-06-04 70 views
0

我正在嘗試創建一個創建模型對象頁面。我用C#使用asp.net mvc。在我的項目中,我試圖創建一個圖書館應用程序,它有圖書,我們可以從應用程序中添加圖書。所以我創建這樣的控制器,無法上傳文件ASP.NET MVC

[HttpPost] 
    public ActionResult Create([Bind(Exclude = "id,bringBack,borrower,isBorrowed")]Book bookToCreate, HttpPostedFileBase picture1) 
    { 
     try 
     { 
      if (picture1.ContentLength > 0) 
      { 
       var fileName = Path.GetFileName(picture1.FileName); 
       var path = Path.Combine(Server.MapPath("~/App_Data/pictures"), fileName); 
       picture1.SaveAs(path); 
      } 

      // TODO: Add insert logic here 
      _entities.AddToLibrary(bookToCreate); 
      _entities.SaveChanges(); 

      return RedirectToAction("ListBooks"); 
     } 
     catch 
     { 
      return View(); 
     } 
    } 

和我的看法是這樣的,

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication2.Models.Book>" %> 

<!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>Create</title> 
</head> 
<body> 
<% using (Html.BeginForm(new { enctype = "multipart/form-data" })) 
    {%> 
    <%: Html.ValidationSummary(true) %> 

    <fieldset> 
     <legend>Fields</legend> 

     <div class="editor-label"> 
      <%: Html.LabelFor(model => model.name) %> 
     </div> 
     <div class="editor-field"> 
      <%: Html.TextBoxFor(model => model.name) %> 
      <%: Html.ValidationMessageFor(model => model.name) %> 
     </div> 

     <div class="editor-label"> 
      <%: Html.LabelFor(model => model.author) %> 
     </div> 
     <div class="editor-field"> 
      <%: Html.TextBoxFor(model => model.author) %> 
      <%: Html.ValidationMessageFor(model => model.author) %> 
     </div> 

     <div class="editor-label"> 
      <%: Html.LabelFor(model => model.picture) %> 
     </div> 
     <div class="editor-field"> 
      <%: Html.TextBoxFor(model => model.picture) %> 
      <%: Html.ValidationMessageFor(model => model.picture) %> 
     </div> 
     <input type='file' name='picture1' id='picture1' /> 
     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 

<% } %> 

<div> 
    <%: Html.ActionLink("Back to List", "Index") %> 
</div> 

我已經嘗試了很多事情,但我不能上傳任何文件。我能做什麼?

+1

是什麼問題?是'picture1' null? –

回答

0

嘗試從Request取得發佈的文件。

var picture1 = this.Request.Files["picture1"]; 
+0

-1這不是非常mvc友好。 –

+0

現在我可以獲取該文件,我更改了我的BeginForm的參數。但我無法保存文件。我能爲此做些什麼?我如何更改文件權限? –

+0

@Daniel A White,然後提供一個更好的答案,而不僅僅是批評。 – Gabe

0

在你的書模式應該是一個preperty

HttpPostedFileBase picture1