Asp.net mvc 3 通过Ajax在ASP.NET MVC3中上载文件不起作用
通常我已经在mvc3中提交了一个文件。现在我需要在Ajax中执行同样的操作。所以我使用了这个jquery插件: 查看代码:Asp.net mvc 3 通过Ajax在ASP.NET MVC3中上载文件不起作用,asp.net-mvc-3,forms,jquery,Asp.net Mvc 3,Forms,Jquery,通常我已经在mvc3中提交了一个文件。现在我需要在Ajax中执行同样的操作。所以我使用了这个jquery插件: 查看代码: $(document).ready(function () { var options = { url: "/Home/TakeFile", dataType: "json", success: showResponse }; $("#File").s
$(document).ready(function () {
var options = {
url: "/Home/TakeFile",
dataType: "json",
success: showResponse
};
$("#File").submit(function () {
alert("submit");
$(this).ajaxSubmit(options);
return false;
});
});
function showResponse(responseText, statusText, xhr, $form) {
alert("showResponse");
alert(responseText.fileName);
}
</script>
@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
<input type="file" id="file" />
<input type="submit" value="Click to submit" id="button" />
}
我的“TakeFile”方法中的file参数始终为null。似乎无法使其正常工作。另外,我们可以使用“Ajax.BeginForm()”帮助程序来完成吗???尝试使用以下命令
<input type="file" id="file" name = "attachment"/>
上载文件时,选项中的
dataType:json
似乎很奇怪,您是否尝试将其删除
还可以尝试在输入类型中使用Name
属性
<input type="file" id="file" name="file" />
好的,您不允许通过ajax上传文件。。。发布文件需要完整回发 你需要一个闪光的解决方案或类似的东西,以使它发生。 例如使用
提交表单后,使用
中
html元素的名称属性来引用表单数据
注意:只有具有name属性的表单元素在提交表单时才会传递其值
由于操作方法public ActionResult TakeFile(HttpPostedFileBase file){..}
有一个参数名“file”,因此在视图中,file输入元素应该有一个name='file'
属性。更新代码:
@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" value="Click to submit" id="button" />
}
@使用(Html.BeginForm(“TakeFile”,“Home”,FormMethod.Post,new{@id=“File”,enctype=“multipart/formdata”}))
{
}
文件只是不上传……否则它会转到控制器中的相应方法,我还可以发送一个响应,该响应在“showResponse()”中正确接收。事实上,“datatype”告诉您从服务器得到的响应类型,而不是向它发出的请求。是的。我只是看到表单的id与输入类型的id相同..哦..是的..将更改任何一个id,这是因为您也在发送Ajax请求。停止Ajax请求并重试,这应该可以工作,因为我以前使用过此代码。谢谢。这是唯一的缺陷。输入类型的name属性遗漏了!!是的。即使我使用的是一个插件,一个不同的插件。你在用什么?我没有为我的案例找到最好的解决方案。这个插件工作得很好:仍然需要在我的实际项目中使用它,然后看看。这段代码是一个示例。
<input type="file" id="file" name="file" />
@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
<input type="file" id="file" name="file" />
<input type="submit" value="Click to submit" id="button" />
}