简体   繁体   中英

Passing data between controller and view with strongly typed model

I have a little bit of a problem with communicate between the controller and a view.

UploadFile (Class):

    public class UploadFile
    {
        public string OrignialFilePath { get; set; }
        public string FilteredFilePath { get; set; }
        public string Name { get; set; } 

        public UploadFile(string x, string y, string z)
        {
            OrignialFilePath = x;
            FilteredFilePath = y;
            Name = z;
        } 
    }

Files (Class):

 public class Files
{

    public List<UploadFile> list { get; set; }

    public Files()
    {
        list = new List<UploadFile>();
    }
}

Controller: (I get files with HTTP POST to this controller)

  Files fileList = new Files();
        foreach (var file in Files)
        {
            UploadFile fu = new UploadFile(file.x, file.y, file.z); 
            fileList.list.Add(fu);
        }

        return RedirectToAction("Result");

Result: (Strongly-typed view)

@model IEnumerable<SelectorITSelectorIT.Models.Files>

@{
    ViewBag.Title = "Result";
}

<h2>SelectorIT - Result</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
    </tr>

@foreach ( var item in Model) {
    <tr>
        <td>
            @item.list  ?????
        </td>
    </tr>
}

</table>

In the foreach var item in model

When i write @item.list i cant go to the files within some index of the list ( i have there UploadFile instance).

I need in the foreach statement : foreach var item in model.list but it doesn't let me, how can i do it?

My Main goal is to Simply display in a table details about each UploadFile in the list of the model("Files").

How can i do it ?

Yes, I you need to use the .list property that you defined in Files and you need to change your view model to simply

@model SelectorITSelectorIT.Models.Files

...

@foreach (var item in Model.list) {
    <tr>
        <td>@item.Name</td>
    </tr>
}

On the other hand, if you really want an IEnumerable of Files, you need to rewrite your loop similar to this:

@foreach (var item in Model) {
    foreach(var file in item.list)
    {
        <tr>
            <td>@file.Name</td>
        </tr>
    }
}

But based on your question, I'm thinking you really just want a model of Files since it already has the list of UploadFiles in it.

You said "i cant go to the files within some index of the list"

You cannot Index a foreach loop, if you want to display a Particular range of Indexes you need to use a For Loop,

for (int i = 0; i < Model.list.Count; i++)
{
  @Html.LabelFor(x => Model.list[i].Name)   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM