MVC 視圖與控制器傳值的幾種方法

1、頁面取值傳給控制器web

 

一、表單傳值----利用Actionajax

 

 

視圖頁:
        <form action="方法名" method="post">
            <label for="content">值內容</label>
            <input type="text"  name="bdzhi" id="content" /><br />
            <input type="submit" value="表單傳值">
        </form>
   控制器:
         public ActionResult 方法名(FormCollection fc)
        {
            ViewBag.message = fc["bdzhi"];
            return View();
        }
        這裏是經過ViewBag返回頁面

         public ActionResult 方法名()
        {
            ViewBag.message =Request.Form["bdzhi"];
            return View();
        }

 

二、AJAX傳值app

    <div>
        <h2>AJAX傳值</h2>
        <span id="sex"></span><br />
        <input type="radio" name="sexs" checked="checked" value="男">男     <input type="radio" name="sexs" value="女">女<br />
        <input type="button" value="提交" id="bt">
        <script>
            //提交按鈕綁定點擊事件
            $("#bt").on('click', function () {
                //獲取選中的radio選項的值
                var value = $("input[type=radio]:checked").val()
                //後臺經過Request.Form["value"]能夠取到
                params = "value=" + value;
                $.ajax({
                    //post方法傳值
                    type: "POST",
                    url: "/xuexi/xingbie",
                    data: params,
                    success: function (data) {
                        //清空id=sex的span標籤裏的內容
                        $("#sex").empty();
                        //將後臺返回的數據添加到span標籤裏
                        $("#sex").append(data);
                    }
                })
            })
        </script>
    </div>        
        控制器:        
        public string xingbie(string sex)
        {
            sex = "您的性別是" + Request.Form["value"];
            return sex;
        }

 

2、控制器返回頁面post

一、使用ViewBag(視圖包)傳遞數據url

         控制器中:ViewBag.屬性="任意";spa

         頁面中:   @ViewBag.屬性orm

         屬性能夠隨便填寫!!!對象

例如:事件

控制器中方法:ip

        public ActionResult 方法()

        {

            ViewBag.message ="哈哈哈";

            return View();

        }

頁面中便可直接使用:

        <span>@ViewBag.message</span>

二、使用View Data傳遞數據

         控制器中:ViewData["隨意起"]="任意";

         頁面中:   @ViewData["隨意起"]

使用方法同上

三、使用TempData傳遞數據

         控制器中:TempData["隨意起"]="任意";

         頁面中:   @TempData["隨意起"]

使用方法同上

        注意!TempData的值在取了一次後則會自動刪除刷新頁面,則TempData[""]爲Null

只是聽說哈~~我沒試驗過,大家能夠試驗下告訴我!!

四、提供視圖模型對象

控制器中:

             public ViewResult Index()  
            {  
            DateTime date = DateTime.Now;  
                return View(date);  
            }
   視圖:
            @model DateTime 
            @{  
                 ViewBag.Title = "Index";  
               }  
            <h2>Index</h2> 
            今天是: @Model.DayOfWeek
相關文章
相關標籤/搜索