簡體   English   中英

無法在POST上綁定MVC模型

[英]Unable to Bind MVC Model on POST

我正在編寫一個顯示經理列表的視圖。 管理員在其名稱旁邊有復選框,以選擇將其從經理列表中刪除。 我在將表單提交綁定回我的視圖模型時遇到問題。 這是頁面的樣子:

在此輸入圖像描述

這是頁面的ViewModel。

public class AddListManagersViewModel
{
    public List<DeleteableManagerViewModel> CurrentManagers;
}

這是每個DeleteableManagers的子ViewModel:

public class DeleteableManagerViewModel
{
    public string ExtId { get; set; }
    public string DisplayName { get; set; }

    public bool ToBeDeleted { get; set; }
}

這是主視圖的代碼:

@model MyApp.UI.ViewModels.Admin.AddListManagersViewModel
<div class="row">
    <div class="span7">
        @using (Html.BeginForm("RemoveManagers","Admin"))
        {
            @Html.AntiForgeryToken()
            <fieldset>
                <legend>System Managers</legend>

                <table class="table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Remove</th>
                        </tr>
                    </thead>

                    <tbody>
                        @Html.EditorFor(model => model.CurrentManagers)
                    </tbody>
                </table>
            </fieldset>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">Delete Selected</button>
            </div>
        }
    </div>
</div>

這是我為DeleteableManagerViewModel創建的EditorTemplate:

@model MyApp.UI.ViewModels.Admin.DeleteableManagerViewModel

<tr>
    <td>@Html.DisplayFor(model => model.DisplayName)</td>
    <td>
        @Html.CheckBoxFor(model => model.ToBeDeleted)
        @Html.HiddenFor(model => model.ExtId)
    </td>
</tr>

但是當我將表單提交給控制器時,模型會返回null! 這就是我想要的:

[HttpPost]
public virtual RedirectToRouteResult RemoveManagers(AddListManagersViewModel model)
{
    foreach (var man in model.CurrentManagers)
    {
        if (man.ToBeDeleted)
        {
            db.Delete(man.ExtId);
        }           
    }
    return RedirectToAction("AddListManagers");
}

我試着跟着這篇文章: CheckBoxList多個選擇:模型中的難度綁定但我必須遺漏一些東西....

謝謝你的幫助!

嗯。 我認為這最終是問題; 這是你在擺姿勢:

CurrentManagers[0].ToB‌​eDeleted=true&CurrentManagers[0].ToBeDeleted=false&CurrentManagers[0].Ext‌​Id=X00405982144

您的模型是一個AddListManagersViewModel ,它AddListManagersViewModel CurrentManagers 所以,你發布了一個DeleteableManagerViewModel數組,它沒有被綁定到“包裝器”模型。 您可以嘗試將模型參數更改為

params DeleteableManagerViewModel[] model

我不會使用EditorFor擴展,所以我只是在猜...

暫無
暫無

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

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