2014-01-13 54 views
0

當我點擊嵌套表單提交按鈕來上傳文件時,它會觸發客戶端驗證,並且我想阻止此操作。
我已經嘗試過兩種獨立的表單元素,它的工作原理。但我必須使用嵌套的表單元素,因爲這是要求(用於設計目的)。如何從嵌套表單上傳文件並阻止客戶端驗證MVC 4中的主表單?

以下是我的代碼。

查看代碼

@using (Html.BeginForm("AddEdit", "Leads", FormMethod.Post, new { @Id = "frmSaveLead", @class = "form-horizontal" })) 
    { 
     @Html.TextBoxFor(model => model.stTitle, new { @class = "m-wrap span12",  @placeholder = "Lead Title", @maxlength = "100" }) 

     @Html.ValidationMessageFor(model => model.stTitle) 

     @Html.TextAreaFor(model => model.stNote, new { @class = "m-wrap span12", @placeholder = "Lead Note" }) 

     @Html.ValidationMessageFor(model => model.stNote) 

     @using (Html.BeginForm("FileUpload", "Leads", FormMethod.Post, new { @Id = "frmFileUpload", @enctype = "multipart/form-data" })) 
     { 

      <span class="btn green fileinput-button"><i class="icon-plus icon-white">    </i> 
      <span>Add file...</span> 
      <input type="file" name="files"> 
      </span> 

      <button type="submit" class="btn blue start"> 
        <i class="icon-upload icon-white"></i><span>Start upload</span> 
      </button> 
     } 

     <button type="submit" class="btn blue"> 
      <i class="icon-ok"></i>Save 
     </button> 
    } 
+0

「我必須使用嵌套的表單元素,因爲這是要求」這是一個可怕的要求,看到如何根據HTML規範不允許嵌套表單。 –

+0

@Marek,是的,我知道,這是不正確的方式。但是爲了設計目的。 – Chintan

+0

你可以嘗試發送表單爲JSON使用jQuery – Nilesh

回答

1

你內心的形式

<form id="login-form"> 
    <input type="file" name="photo" id="files" accept="image/*;capture=camera"> 
    <button type="button" onclick="submitform()">Submit</button> 
    </form> 

jQuery的

function submitform(){ 
     var postdata = $('#login-form').serialize();   
     var file = document.getElementById('files').files[0]; 
     var fd = new FormData(); 
     fd.append("files", file); 
     var xhr = new XMLHttpRequest(); 
     xhr.open("POST", "/Home/Index", false); 
     xhr.send(fd);  
    } 

控制器

[HttpPost] 
    public JsonResult Index(FormCollection data) 
    { 

     if (Request.Files["files"] != null) 
     { 
      HttpPostedFileBase file = Request.Files["files"]; 
     } 
     return Json(something); 
    } 
+0

Imagefile是否等同於HttpPostedFileBase的類型? – Chintan

+0

是的,它相當於HttpPostedFileBase的類型 – Nilesh

+0

好的,我會試試這個。回頭見。謝謝。 – Chintan