iT邦幫忙

1

抓取View IEnumerable的輸入內容

各位:

我有個table叫"customer
public partial class customer
{        
    public string cust_id { get; set; }
    public string cust_name { get; set; }
}
在controller讀取資料後傳到前端的view

controller如下:    
public ActionResult form03()
{            
    return View(db.customer.ToList());
}

view如下:
@model IEnumerable<customer>

@using (Html.BeginForm())
{

    <input type="submit" value="Submit" /><br />
    <table>
        <tr>
            <td>Customer ID</td>
            <td>Customer Name</td>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.EditorFor(model => item.cust_id)
                </td>
                <td>
                    @Html.EditorFor(model => item.cust_name)
                </td>
            </tr>
        }
    </table>
}

請問各位大大, 我在按Submit後, 如何讀取輸入的資料
看更多先前的討論...收起先前的討論...
小魚 iT邦大師 1 級 ‧ 2017-06-18 18:19:13 檢舉
你有注意按下Submit之後,程式跑到哪裡了嗎?
在後端有讀HttpPost的程式碼嗎?
EditorFor我沒用過,不過你可以在網頁用開發人員工具,
看它在Html實際的標籤是什麼,還有他的Name是什麼,
後端接資料最主要是用Name來接資料的。
felix0624 iT邦新手 5 級 ‧ 2017-06-18 20:27:05 檢舉
其實如果是單筆資料, 我都可以抓到資料, 現在是顯示多筆資料, 找遍許多資料, 還是找不到如何接收多筆資料
小魚 iT邦大師 1 級 ‧ 2017-06-18 22:28:37 檢舉
有什麼理由一定要一次讀全部的資料,通常新增編輯修改都是切換到單個Model的頁面,你如果一定要在一個頁面去改,可以試試用html標籤,name改成cust_id[]之類的
felix0624 iT邦新手 5 級 ‧ 2017-06-19 15:42:26 檢舉
小魚感謝你的回答, 只是我不知道你的系統跟user是哪一類的, 但是在我的系統有很多主明細資料在一個畫面要維護, 而明細資料通常都是二,三十個item, 如果讓user一個個點進單一model的畫面去修改, 我早就不知被追殺到哪裡去了, 所以這種多筆的維護是有其必要性的
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
石頭
iT邦高手 1 級 ‧ 2017-06-19 14:30:26

如果你真的要抓多筆資料
你就無法用MVC預設的Model Binding

你可以試試使用

HttpContext.Request.Form;
HttpContext.Request.QueryString

來處理表單提交的資料

felix0624 iT邦新手 5 級 ‧ 2017-06-19 15:34:14 檢舉

其實早上終於找到解決的方法了, 就是將foreach改為for, IEnumerable改為List就可以了

修正後的View如下
@model List<customer> ==>修改
@using (Html.BeginForm())
{
    <input type="submit" value="Submit" /><br />
    <table>
        <tr>
          <td>Customer ID</td>
          <td>Customer Name</td>
        </tr>
        @for (int i = 0; i < Model.Count; i++) ==>修改
        {
        <tr>
          <td>@Html.EditorFor(m => m[i].cust_id)</td> =>改
          <td>@Html.EditorFor(m => m[i].cust_name)</td>
         </tr>
        }                    
    </table>
}

接收的controller
 [HttpPost]
 public ActionResult form03(List<customer> model)
 {
     customer customers;
     List<customer> list = new List<customer>();

     for (int i=0;i<model.ToList().Count;i++)
     {
         customers = model[i];
         list.Add(customers);
     }
     return View(list);
 }

我要發表回答

立即登入回答