2014-05-20 60 views
0

型號MVC綁定視圖控制器

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

控制器

(試圖從一個特定的文件夾中獲取文件)的文件名來了,既包含單詞「僱員」然後我在文件名中搜索一個字符串並採取一些操作。

[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還是falsecheckedunchecked),但我無法訪問文件名。

回答

1

變化

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

要:

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

有必要產生一個字段的正確數據綁定

+0

它的工作,也有一些更多的problems.Thanks! :) –

+0

+1由於OP注意到你的答案對他有效,但他們沒有奇怪地贊成。 –

+0

我只能感到難過 –