Ujjwal Vaish
Ujjwal Vaish

Reputation: 375

MVC Binding views to controllers

Model

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

Controller

(Trying to get files from a particular folder) File names are coming , both contain the word "employee" Then I am searching for a string , in the file name and taking some actions.

[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");
}    

View

@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>

In this program , I am trying to access the checkboxes as well as the file names for each object passed in the view. I am able to access the checkbox and know whether it is true or false ( checked or unchecked ) but I'm not able to access the file names.

Upvotes: 0

Views: 58

Answers (1)

Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

Change

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

To :

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

it is necessary to generate a field for the correct data binding

Upvotes: 1

Related Questions