4

I have a PostEditViewModel class

 public class PostCreateViewModel
{
    public int PostId { get; set; }
    public string Title { get; set; } 
    public string Body { get; set; } 

    public string Descrition { get; set; } 
    public string Category { get; set; }

    public List<IFormFile> Images { get; set; } 
    public List<ImagePath> ExistingPhotoPaths { get; set; }
}

and ImagePath class

public class ImagePath
{
    public int ID { get; set; }
    public string Path { get; set; }
}

in my edit view i try to hide the ExistingPhotoPaths property as

<input hidden asp-for="PostId" />

    @foreach (var path in Model.ExistingPhotoPaths)
    {
        i = i++;
        string x = val + i.ToString();
        <input type="hidden" name="ExistingPhotoPaths.Index" value="@x" />
        <input type="hidden" name="ExistingPhotoPaths[@x].Key" value="@path.ID" />
        <input type="hidden" name="ExistingPhotoPaths[@x].Value" value="@path.Path" />
    }

where val is a string used for binding Non-Sequential Indices mentioned in ASP.NET Core Model Bind Collection of Unknown Length this question.

But using this method also my ExistingPhotoPaths property returning collection of null. i.e for suppose while get request ExistingPhotoPaths contains 3 ImagePath objects on post request it returning array of 3 null objects see below image, on post request see what ExistingPhotoPaths contains.

enter image description here

Am i using it correct way or suggest me to better way to do it and where i went wrong in my way.

Ramesh Kumar
  • 1,241
  • 1
  • 9
  • 15

1 Answers1

5

You need to do it like this:

@for (var i = 0; i < Model.ExistingPhotoPaths.Count; i++)
{
    <input type="hidden" asp-for="ExistingPhotoPaths[i].ID" />
    <input type="hidden" asp-for="ExistingPhotoPahts[i].Path" />
}

The syntax you're using currently, is for binding to a dictionary, not a list of objects, and foreach isn't going to work here, as Razor needs the entire model expression path to build the right input names.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444