2013-07-25 40 views
1

我創建了一個樣本MVC應用程序來測試文件上傳我讀這個有用post並做到這一點,但客戶端驗證工作沒有,給我錯誤我所有的代碼是:爲什麼文件上傳不起作用?

我重視這些在赫德標籤:

<script src="~/Scripts/jquery-1.8.2.min.js"></script> 
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script> 
<script src="~/Scripts/jquery.validate.min.js"></script> 
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script> 
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> 

我的模型:

public class FIleModel 
{ 
    [Required, FileExtensions(Extensions = "csv", ErrorMessage = "Specify a CSV file. (Comma-separated values)")] 
    public HttpPostedFileBase myFile { get; set; } 
} 

錯誤:

Unhandled exception at line 4, column 9003 in http://localhost:6284/Scripts  
/jquery.validate.min.js 
    0x800a138f - JavaScript runtime error: Unable to get property 'call' 
    of undefined or null reference 

對我而言:

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
     @Html.ValidationSummary(); 
     <fieldset> 
      <legend>Registration Form</legend> 
      <ol> 
       <li class="lifile"> 
        @Html.TextBoxFor(m => m.myFile, new { type = "file" }) 
        @Html.ValidationMessageFor(m => m.myFile) 

       </li> 
      </ol> 
      <input type="submit" id="btnSubmit" value="Upload" /> 
     </fieldset> 
    } 
+0

看看http://stackoverflow.com/questions/14659023/error-in-jquery-validate-js-in -mvc-4-project-with-jquery-1-9 –

回答

0

對於文件上傳,您可以使用此代碼。

在控制器:

[HttpPost] 
public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file) 
{ 
    if (ModelState.IsValid) 
    { 

     //you can validate file here. if okay continue... 

     var filename = Path.GetFileName(file.FileName); 
     var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename); 
     file.SaveAs(path); 
     eventmodel.Url = filename; 

     _db.EventModels.AddObject(eventmodel); 
     _db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    return View(eventmodel); 
} 

,並查看:

<div> 
    Image 
    <input type="file" name="file" id="file" /> 
    @Html.HiddenFor(model => model.ImageUrl) 
    @Html.ValidationMessageFor(model => model.Url) 
</div> 
+0

什麼是輪胎? – whisk

+1

我改變了我的答案。 Tire從我的舊代碼中只剩下一家輪胎公司。感謝您的關注。 –