ASP.NET MVC中實現多個按鈕提交的解決方法

    在MVC開發中,經常會遇到一個頁面中有多個提交按鈕,不同的按鈕對應不同的功能,比如:監控  取消監控

   在webform中我們不討論,但是在ASP.NET MVC 中一個表單只能提交一個Action處理,相對比較麻煩些,下面我們開始實現:


實現方式:

首先Web前端設置功能按鈕的name屬性如:


<input type="submit" value="監控" name="actionForm" />
<input type="submit" value="取消監控"  name="actionForm"/> 


然後在Controller中判斷



//監控用戶資料
        [HttpPost]
        public ActionResult AdminUserProfile(string actionForm,string paramer1,string paramer2)
        {
            if (actionForm == "監控")
            {
                //處理代碼
                return RedirectToAction("TipInfo", "Common", new { area = "Office" });//跳轉至成功頁面
            }
            else if (actionForm == "取消監控")
            {
                //處理代碼
                return RedirectToAction("TipInfo", "Common", new { area = "Office" });//跳轉至成功頁面
            }
            else
            {
                //處理代碼
            }
            return View();
        }

Controller中的代碼還有一種寫法:

  //監控用戶資料
        [HttpPost]
        public ActionResult AdminUserProfile(FormCollection collection)
        {
            if (collection.Count > 0)
            {
                if (collection["actionForm"] == "監控")
                {
                    //處理代碼
                    return RedirectToAction("TipInfo", "Common", new { area = "Office" });//跳轉至成功頁面
                }
                else if (collection["actionForm"] == "取消監控")
                {
                    //處理代碼
                    return RedirectToAction("TipInfo", "Common", new { area = "Office" });//跳轉至成功頁面
                }
                else
                {
                    //處理代碼
                }
            }
            return View();
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章