2

Here is my ViewModel

public class VideoViewModel
{
    public string Movie { get; set; }
    public int Order { get; set; }

    public IList<VideoContent> VideoContents { get; set; }
}

How can I pass data from fields in view to controller mapped to my collection in my viewModel?

This code in my view is passing Movie and Order to controller but I can't figure out hos to send the collection too.

@model ViewModels.VideoViewModel
    <form method="post">
        <div class="form-group">
            <label for="movie">Movie</label>
            <input type="text" name="Movie" id="movie" class="form-control">
        </div>
        <div class="form-group">
            <label for="order">Order</label>
            <input type="text" name="Order" id="order" class="form-control">
        </div>            
        <button type="submit" class="btn btn-primary">Add to database</button>
    </form>

Thanks in advance!

/ Kalle

1 Answer 1

5

ASP .NET Core uses the name attribute to bind the data from the input fields to the view model.

This should work for passing the collection.

for(int c = 0; c < VideoContents.Count; c++)
{      
    <input name="VideoContents[@c].FirstProperty" value="@Model.VideoContents[@c].FirstProperty"/>
    <input name="VideoContents[@c].SecondProperty" value="@Model.VideoContents[c].SecondProperty"/>
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! You have saved my day :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.