簡體   English   中英

從多個文本框中提取用戶輸入並將其作為列表傳遞回控制器

[英]Pull user input from multiple textboxes and pass as list back to controller

我有一個由多個局部視圖組成的視圖,每個局部視圖為最終將存儲在多個表中的數據創建用戶輸入字段:每個局部視圖一個。

我可以將單行數據寫回到數據庫中。 在下面,.Add(primary)可以正常工作,因為主表始終只有一個名字和姓氏。

但是,有時給定回發會有多個電話號碼。 我需要將它們中的每一個加載到電話表列表中,然后在Create方法中將它們拉出,對嗎? 這是我控制器的當前Create方法。

    public ActionResult Create(PrimaryTable newprimary, List<PhoneTable> newphone)
    {
        if (ModelState.IsValid)
        {


            db.PrimaryTables.Add(newprimary);


            foreach (var phone in newphone)
            {
                phone.CareGiverID = newCareGiverID;
                db.tblPhones.Add(phone);
                db.tblPhones.Last().CareGiverID = newCareGiverID;
            }


            db.SaveChanges();
            return RedirectToAction("Index");
        }

和我當前的手機局部視圖。

@model IList<FFCNMaintenance.Models.PhoneTable>



<div>
<label class="label-fixed-width">Phone:</label>
@Html.TextBox("Phone1", null, new { style = "width: 600px" })
<br />
<label class="label-fixed-width">Phone:</label>
@Html.TextBox("Phone2", null, new { style = "width: 600px" })
<br />



</div>

但是,很明顯,僅將它們命名為Phone1和Phone2並不會自動將它們加載到Phone表類型列表中。

有什么想法嗎?

HTTP可以正常工作。 它對列表或C#一無所知。 您必須將參數綁定到服務器端的列表。

在您的控制器中,您將可以訪問Request.Params對象中的Phone1Phone2等。 Request.Params是所有字段(查詢字符串,表單字段,服務器變量,Cookie等)的組合。

如果希望這些字段從View自動映射到控制器方法中的參數(即List<PhoneTable> ),則可以實現自己的客戶ModelBinder

這是一個快速(未經測試)的示例,可讓您大致了解自定義模型聯編程序的工作方式。

public class PhoneModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // If not the type that this binder wants, return null.
        if (!typeof(List<PhoneTable>).IsAssignableFrom(bindingContext.ModelType))
        {
            return null;
        }

        var phoneTable = new List<PhoneTable>();

        int i = 1;

        while (true)
        {
            var phoneField = bindingContext.ValueProvider.GetValue("Phone" + i.ToString());

            if (phoneField != null)
            {
                phoneTable.Add(new PhoneTable() { Number = phoneField.AttemptedValue });
                i++;
                continue;
            }

            break;
        }

        return phoneTable;
    }
}

要注冊此資料夾,您需要將其添加到模型資料夾的集合中,或使用自定義的模型資料夾提供程序來確定要使用的模型資料夾。 這是將其簡單地添加到模型綁定程序集合中的方法。

ModelBinders.Binders.Add(typeof(List<PhoneTable>), new PhoneModelBinder());

暫無
暫無

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

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