Get items from listbox in controller MVC ASP 4

时间秒杀一切 提交于 2019-12-03 15:33:21

The reason why it is not deserializing is because the form data posted back does not match the format that MVC is expecting for array mapping.

To approach what you are trying to accomplish, I would recommend creating another model to represent the form posted data. In this case:

public class SelectedGenrePostModel
{
    public int ChannelId { get; set; }
    public List<int> ChosenGenres { get; set; }
}

And in your view, have javascript hook into the submit event to automatically select all of the options in ChosenGenres so they are properly posted back according to what your UI is doing.

<script type="text/javascript">
    $(function () {
        // this event fires when the browser is about to submit a form
        $('#GenreForm').submit(function () {
            // modifies the 'selected' options on the list 
            // before finally being submitted by the browser
            $('#ChosenGenres option').prop('selected', true);
        });
    });
</script>

Then, if you absolutely need the SelectGenreModel, you repopulate using your service call and the data posted back via SelectedGenrePostModel.

public ActionResult CreateNewChannel(GuiChannel channel, int? userId, SelectGenrePostModel model)
{
    if (userId.HasValue)
    {
        // do work here
        return RedirectToAction("SelectChannel", new { channelId = channelId, userId = userId });
    }
    return RedirectToAction("Index", "Home");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!