MVC:如何从HttpPostedFileBase知道哪个输入值 [英] MVC: How to know which input value from HttpPostedFileBase

查看:81
本文介绍了MVC:如何从HttpPostedFileBase知道哪个输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我首先尝试尽可能简单地解释我的情况:

Let me try to explain my situation as simple as possible first:

假设我有一个包含多个[input type ='File']的页面.其中一些可能被选择为文件,而某些则未被选择.

Suppose I have a page which contains multiple [input type='File']. Some of them may be selected a file and some are not.

在我的httppost方法中,我知道我需要使用"IEnumerable files"之类的参数来获取文件名,而且每个[input]名称我都应定义='files'或'files [0]','files [ 1]',等等.....

In my httppost method, I know I need to use parameter like "IEnumerable files" to get filenames, and also each [input] name I should define either = 'files' or 'files[0]','files[1]', etc.....

我的问题是:获取HttpPostedFileBase列表时,如何确定哪个文件属于哪个输入控件?由于某些输入可能留空.

My question is: when getting a list of HttpPostedFileBase, how could I determine which file belongs to which input control? As some inputs may leave blank.

此外,由于这些[input]是动态创建的,并且没有固定数量,因此我无法在httppost方法中为每个参数硬编码该参数.

Also because these [input] are created dynamically and there is no fixed number of it, I could not hard-code the parameter in httppost method for each of them.

推荐答案

尝试以下解决方案:

查看:

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input type="file" name="file1" />
    <input type="file" name="file2"/>
    <input type="file" name="file3"/>
    <input type="file" name="file4"/>
    <input type="file" name="file5"/>

    <input type="submit" value="go" />
}

控制器:

  var uploaded = Request.Files.AllKeys
      .Select(x => new {file = Request.Files[x], name = x})
            .Where(x => x.file.ContentLength > 0).ToList();

已上传"匿名类型将包含属于输入控件名称的文件,并且仅包含选择了输入的名称

The "uploaded" anonymouse type will contains file belonging to input control name, and will conatins only input names which selected

这篇关于MVC:如何从HttpPostedFileBase知道哪个输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆