[英]FormData Values in Razor HTML page, getting in C# Method
I have following input element in razor view page 我在剃刀视图页面中有以下输入元素
<input type="file" id="uploadFile" name="FileUpload" multiple="multiple" />
using following script I'm binding data to this ForData 使用以下脚本,我将数据绑定到此ForData
$('#uploadFile').on('change', function()
{
var fd = new FormData();
var files = $('#uploadFile')[0].files;
for (var i = 0; i < files.length; i++)
{
if (files[i].size < 5242880)
{
fd.append("myFiles", files[i])
}
}
});
I'm trying to get these files in C# method like following 我正在尝试使用C#方法获取这些文件,如下所示
[HttpPost]
public ActionResult SomeAction(ModelClass model)
{
var attchaedfiles = System.Web.HttpContext.Current.Request.Files["myFiles"];
for (int i = 0; i < attchaedfiles.Count; i++)
{
if (!string.IsNullOrEmpty(attchaedfiles[i].FileName))
{
....
}
}
}
but here I'm getting folllowing errors 但在这里我得到以下错误
Operator '<' cannot be applied to operands of type 'int' and 'method group'
运算符“ <”不能应用于类型为“ int”和“ method group”的操作数
Cannot apply indexing with [] to an expression of type 'System.Web.HttpPostedFile'
无法将带有[]的索引应用于类型为'System.Web.HttpPostedFile'的表达式
In your ajax script, make sure you include these: 在ajax脚本中,确保包括以下内容:
$.ajax({
url: yourUrl,
type: 'POST',
// Needed for FormData submit
processData: false,
// Needed for FormData submit
contentType: false,
data: fd,
dataType: 'json',
success: function () {
// Success things
},
error: function () {
// Error things
},
complete: function () {
// Complete things
}
});
And that your form code includes enctype = "multipart/form-data": 并且您的表单代码包括enctype =“ multipart / form-data”:
@using (Html.BeginForm(null, null, FormMethod.Post, new { @action = YourAction, id = "your_id", enctype = "multipart/form-data" }))
Try the following approach that checks possible conditions regarding to file uploads: 尝试以下方法检查有关文件上传的可能条件:
Model: 模型:
public class ExperimentViewModel
{
public int Id { get; set; }
[DataType(DataType.Upload)]
public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
//other properties
}
Controller: 控制器:
if (model.FileUpload != null)
{
if (model.FileUpload.Count() > 0)
{
foreach (var upload in model.FileUpload)
{
if (upload != null && upload.ContentLength > 0)
{
//your stuff
}
}
}
}
You can also look at my answer on How to display images in MVC . 您也可以查看有关如何在MVC中显示图像的答案。
Hope this helps... 希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.