2012-07-08 24 views
0

我有能力上传文件并将其保存到目录。这很好。我需要在数据库中输入关于该文件的信息。到目前为止,我不知道如何在这个特殊情况下将视图中的值传递给控制器​​。我曾尝试将它作为方法参数传递,但该值未发布。如何通过MVC3中的ajax表单传递值?

这里是我的剃刀形式:

@using (Html.BeginForm("AjaxUpload", "Cases", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" })) 
     { 
     <fieldset> 
     <legend>Upload a file</legend> 
     <label>File to Upload: <input type="file" name="file" />(100MB max size)</label> 

     <input id="ajaxUploadButton" type="submit" value="Submit" /> 

     </fieldset> 
     } 
    <div id="attachments"> 
     @Html.Partial("_AttachmentList", Model.Attachments) 
    </div> 

这里是我的jQuery来ajaxify形式:

$(function() { 
    $('#ajaxUploadForm').ajaxForm({ 
     iframe: true, 
     dataType: "json", 
     beforeSubmit: function() { 
      $('#ajaxUploadForm').block({ message: '<h1><img src="/Content/images/busy.gif" /> Uploading file...</h1>' }); 
     }, 
     success: function (result) { 
      $('#ajaxUploadForm').unblock(); 
      $('#ajaxUploadForm').resetForm(); 
      $.growlUI(null, result.message); 
      //$('#attachments').html(result); 
     }, 
     error: function (xhr, textStatus, errorThrown) { 
      $('#ajaxUploadForm').unblock(); 
      $('#ajaxUploadForm').resetForm(); 
      $.growlUI(null, 'Error uploading file'); 
     } 
    }); 

}); 

这里是控制器方法:

public FileUpload AjaxUpload(HttpPostedFileBase file, int cid) 
     { 
     file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName)); 

     var attach = new Attachment { CasesID = cid, FileName = file.FileName, FileType = file.ContentType, FilePath = "Demo", AttachmentDate = DateTime.Now, Description = "test" }; 
     db.Attachments.Add(attach); 
     db.SaveChanges(); 

     //TODO change this to return a partial view 
     return new FileUpload { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } }; 
     } 

我想CID传递给此方法,以便我可以将记录插入到数据库中。

回答

1

你可以把它作为表单里面的隐藏字段:

@Html.Hidden("cid", "123") 

或作为路由值:

@using (Html.BeginForm(
    "AjaxUpload", 
    "Cases", 
    new { cid = 123 }, 
    FormMethod.Post, 
    new { enctype = "multipart/form-data", id = "ajaxUploadForm" } 
)) 
{ 
    ... 
} 
+0

这伟大工程!我使用了路由值。我不知道为什么我没有想到这一点!感谢您的快速回复。 – Ryan 2012-07-08 20:54:29