how to pass list of object from view to controller in mvc

first i create list of models in [HttpGet] action and return to view.

public ActionResult Setting()
        var model = db.Settings.ToList();
        return View(model);

them in view get list in view and show good.
but after edit the value of setting i want to pass list of object from view to controller don’t work this.
@model List<TajerWebsite.Models.Setting>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <!-- left column -->
            <div class="col-md-6">
                <!-- general form elements -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">تنظیمات</h3>
                    <!-- /.card-header -->
                    <!-- form start -->
                    @using (Html.BeginForm("Setting","Admin", new { FormMethod.Post }))

                        foreach (var item in Model)
                            <div class="card-body">
                                <div class="form-group">
                                    @Html.HiddenFor(model => item.Id)
                                    <label for="exampleInputPassword1">@item.Name</label>
                                    @Html.EditorFor(model => item.Value, new { htmlAttributes = new { @class = "form-control"} })
                                    @Html.ValidationMessageFor(model => item.Value, "", new { @class = "text-danger" })


                        <!-- /.card-body -->

                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">ذخیره</button>


and action is :
    public ActionResult Setting(IEnumerable<Models.Setting> settings)
        return View(settings);

but settings is null!


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can’t use @foreach loop in the view in order to pass list of object back to the controller, because that would generate input elements with same IDs and Names.

Instead, use standard for loop:

for(int i = 0; i < Model.Count; i++)
    <div class="card-body">
        <div class="form-group">
            @Html.HiddenFor(m => m[i].Id)
            <label for="exampleInputPassword1">@Model[i].Name</label>
            @Html.EditorFor(m => m[i].Value, 
                new { htmlAttributes = new { @class = "form-control"} })
            @Html.ValidationMessageFor(m => m[i].Value, 
                new { @class = "text-danger" })

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x