簡體   English   中英

將ListBoxFor(多個)綁定回Model

[英]Bind ListBoxFor (Multiple) back to Model

我有一個MVC視圖,該視圖使用下面的Razor語法渲染基本上等同於KeyValuePair的內容,然后生成以下HTML。

@Html.DropDownListFor(x => x.SelectedItems, new SelectList(Model.SelectedItems, "Key", "Key"), new { Class = "selectList selectedList", size = "2" })

HTML:

<select class="selectList selectedList" id="SelectedItems" name="SelectedItems" size="2">
   <option value="842">Item 1</option>
   <option value="326">Item 2</option>
   <option value="327">Item 3</option>
</select>

我正在使用Jquery和通用函數手動過帳表單以過帳我們的表單,如下所示:

function GenericSubmit(formSelector, sender, callback) {
    if (typeof (sender) != "undefined" && $(sender).hasClass('disabled')) {
        return false;
    }

    var $that = $(formSelector);
    var that = $that.get(0);
    if ($that.valid()) {
        $.ajax({
            url: that.action,
            type: that.method,
            data: $(that).serialize(),
            success: function (data, textStatus, jqXHR) {
                callback.call(that, data);
            }
        });
    }
    return false;
}

但是我遇到的問題是,只有要發送的數據才是實際值(我希望這就是JQ的工作方式..),但是我需要綁定到IEnumerable。

通過查看發送到表單的POST數據,我只能看到正在發送以下值-我可以預期為什么我的模型具有null集合。

SelectedItems:842
SelectedItems:326
SelectedItems:327

我的模型如下:

/// <summary>
/// An response for dealing with list type entities
/// </summary>
public class ListEntityResponse : EntityScreenResponse
{
    /// <summary>
    /// Contains a Enumerable of items that can be selected
    /// </summary>
    public List<KeyValueViewModel> AvailableItems { get; set; }

    /// <summary>
    /// Contains a Enumerable of items that have been selected
    /// </summary>
    public List<KeyValueViewModel> SelectedItems { get; set; }

    public ListEntityResponse()
    {
        AvailableItems = new List<KeyValueViewModel>();

        SelectedItems = new List<KeyValueViewModel>();
    }


}

為了更加清晰-這是我的KeyValueViewModel:

 public class KeyValueViewModel
    {
        public string Key { get; set; }

        public string Value { get; set; }
    }

當前結果

我為此進行了高低搜尋,但似乎找不到任何可行的主題,我們將不勝感激!

謝謝,

//剛剛意識到我讀錯了你的問題。

如果要綁定到多個值,則需要使用ListBoxFor

//

那么,為什么您的控制器可能需要從視圖中接收所有這些信息(如果后端中可能已經包含了某些信息)呢?

只關心您在表單中提交的內容是有意義的。

如果您需要重新填充此數據以再次呈現視圖(因為存在驗證錯誤,這是一種優雅的方法)

http://www.paulstovell.com/clean-aspnet-mvc-controllers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM