ASP.NET使用ViewBag和HttpPost在MVC中進行自定義類的數據傳遞Demo

第一步創建一個實體類Product

在這裏插入圖片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Product
    {
        public string PName { get; set; }
        public int PNum { get; set; }
    }
}

第二步創建一個空的控制器

在這裏插入圖片描述

在這裏插入圖片描述

該控制器的代碼爲

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost] //這裏如果不標記會報錯的
        public ActionResult Index(Product p)
        {
        //這裏用的實體類接收
            ViewBag.ProductInfo = $"您選擇了名稱爲{p.PName},數量爲{p.PNum}";
            return View();
        }
    }
}

第三步 右鍵添加視圖

在這裏插入圖片描述

在這裏插入圖片描述

第四步 Index頁面



@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
      @*action的路徑要寫對,       method爲post*@
        <form action="/Home/Index" method="post">
                             @*name的名字必須與實體類的屬性相同*@
            <div>名稱:<input type="text" name="PName" /> </div>
            <div>數量:<input type="text" name="PNum" /> </div>
            <input type="submit" value="提交" />
            @*接收的參數*@
            <h1>@ViewBag.ProductInfo</h1>
        </form>

    </div>
</body>
</html>

效果圖

在這裏插入圖片描述

在這裏插入圖片描述

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