我知道这已经讨论了很多次。
我基本上希望在我看来有可能更新文件。此文件必须映射到控制器期望的模型:
public ActionResult Create(Company company)
{
//Do something with the received model
}
模特:
public class Company
{
public int Id { get; set; }
public HttpPostedFileBase PictureUpload { get; set; }
...
}
这没有任何问题。 现在我想通过AJAX发送我的表单数据,包括文件。 因此我在我的观点中使用这个:
@using (Ajax.BeginForm("Create", "Company", null, new AjaxOptions { HttpMethod = "Post", OnSuccess = "ajaxOnSuccess", OnFailure = "alert('Error message.');" }, new { @class = "ym-form", enctype = "multipart/form-data" }))
这基本上有效但文件上传不起作用(据我所知,ajax无法访问该文件,因此无法发送)。
我想要解决这个问题的最佳解决方案,而无需修改我的后端(控制器/型号)。
电子。 G。我读了这篇文章: http://ajeeshms.in/Blog/Article/1/upload-files-using-ajax-in-asp-mvc
它提供了两个很好的可能性,但是我必须修改后端,因为据我所知,我的模型中不能再自动映射到HttpPostedFileBase类型了。
我不介意在我的视图中使用任何有效的插件或仅使用新浏览器支持的技术。
答案 0 :(得分:1)
试试此代码
//添加对form.js的引用
<script src="http://malsup.github.com/jquery.form.js"></script>
@using (Html.BeginForm("Create", "Company", FormMethod.Post, new { @enctype ="multipart/form-data",@id="formid" }))
{
}
//Javascript code
<script type="text/javascript">
$('#formid').ajaxForm(function (data) {
});
</script>
这将作为ajax提交。
//您可以获得有关AjaxForm here
的更多详细信息答案 1 :(得分:0)
请尝试这个@using (Html.BeginForm("Create", "Company", FormMethod.Post, new { id = "ym-form", enctype="multipart/form-data" }))
答案 2 :(得分:0)
我认为您无法使用AJAX上传文件。实现此目的的一种方法是使用隐藏的iframe。试试这个jQuery Form plugin和Telerik file control
请参阅此link。
答案 3 :(得分:0)
我是根据Demian Flavius的答案做出的: How to do a ASP.NET MVC Ajax form post with multipart/form-data?
基本上它是新的JavaScript的FormData对象,可以像上面提到的文章那样使用ajax轻松上传。