MVC将视图绑定到控制器

时间:2014-05-20 06:42:56

标签: asp.net-mvc

模型

public class ImportFiles
{
    public string FileName;
    public bool FileSelected { get; set; }   
}

控制器

(试图从特定文件夹中获取文件)文件名即将出现,两者都包含单词" employee"然后我在文件名中搜索一个字符串并采取一些措施。

[HttpGet]
public ActionResult ImportFiles()
{
    string folderpath = @"C:\Users\uvaish\Documents\Visual Studio 2010\Projects\MVCDemo\MVCDemo\Models";

    string filename = "*";
    string[] fileList = System.IO.Directory.GetFiles(folderpath, filename);//getting the file names from the folder as an array

    List<ImportFiles> inputFiles = new List<ImportFiles>(fileList.Length);//making a list of same number of elements as the number of files            

    foreach (string str in fileList)
    {
        ImportFiles inputFile = new ImportFiles();
        inputFile.FileName = Path.GetFileName(str);
        inputFile.FileSelected = false;
        inputFiles.Add(inputFile);
    }
    return View(inputFiles);
}


[HttpPost]
public string ImportFiles(List<ImportFiles> import)
{
    foreach (ImportFiles importFile in import)
    {
        if (importFile.FileSelected == true)
        {
            if (importFile.FileName.Contains("ployee"))//Getting a null point reference here
            {
                return ("file found");
            }
            else
            {
                return ("no file found");
            }
        }
        else
        {
            return ("no file selected");
        }
    }
    return ("done");
}    

查看

@model IList<ProjectName.Model.ImportFiles>
@using AetnaCoventryMigration.Model;

@using (Html.BeginForm("ImportFiles", "Admin", FormMethod.Post))
{ 
   <div class="panel panel-default">
     <table width="550px" class="mGrid table">
       <tr>
         <th>
            Select
         </th>
         <th>
            File Name
         </th>
       </tr>
       @for (var i = 0; i < Model.Count; i++)
       {
         <tr>
           <td>
              @Html.EditorFor(x => x[i].FileSelected)
           </td>
           <td>
               @Model[i].FileName                                                              
           </td>
         </tr>
       }
    </table>

在这个程序中,我试图访问复选框以及视图中传递的每个对象的文件名。我可以访问该复选框,并知道它是true还是falsechecked还是unchecked),但我无法访问文件名。

1 个答案:

答案 0 :(得分:1)

更改

   <td>
         @Model[i].FileName                                                              
   </td>

致:

   @Html.DisplayFor(x => x[i].FileName)
   or add 
   @Html.HiddenFor(x => x[i].FileName)

必须为正确的数据绑定生成字段