简体   繁体   中英

ASP.NET MVC5. I don't know why my form returns null viewmodel object

I need to check the needed checkboxes to find out whether I need to add the audio to playlist. I see the view with list of all audios and checkboxes but after submitting, the form returns nothing and I don't know why so!

So here's my ViewModel code:

public class AddToPlaylist
{
    public Audio Audio { get; set; }
    public bool IsSelected { get; set; } = false;
}

Controller:

public ActionResult Add()
{
    var item = new List<AddToPlaylist>();
    foreach (var a in db.Audios)
    {
        var cur = new AddToPlaylist();
        cur.Audio = a;
        item.Add(cur);
    }
        return View(item);
    }

    [HttpPost]
    public ActionResult Add(List<AddToPlaylist> playLists)
    {
        return View(playLists);
    }

And View:

@using AudioList.ViewModels

@model List<AddToPlaylist>

<h1>Adding audios...</h1>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <table class="table table-striped">

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Audio.Band.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Audio.Title)
            </td>
            <td>
                @Html.CheckBoxFor(modelItem => item.IsSelected)
            </td>
        </tr>
    }

    </table>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>

Try replacing your foreach loop with a for loop:

@for (var i = 0; i < Model.Count; i++)
{
    <tr>
        <td>
            @Html.DisplayFor(x => x[i].Audio.Band.Name)
        </td>
        <td>
            @Html.DisplayFor(x => x[i].Audio.Title)
        </td>
        <td>
            @Html.CheckBoxFor(x => x[i].IsSelected)
        </td>
    </tr>
}

Also notice that since you are only displaying the Audio.Band.Name and Audio.Title properties and you don't have a corresponding input field in your form you will never retrieve their values on postback. You will only retrieve the selected checkbox values. If you wanted to bind those values as well you might consider including them as hidden fields:

@Html.HiddenFor(x => x[i].Audio.Band.Name)
@Html.HiddenFor(x => x[i].Audio.Title)

For more information about model binding to a list I would recommend you reading the following blog post which explains in details how your input fields should be named so that the ASP.NET MVC model binder is capable of retrieving the values on postback.

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