ASP.NET MVC中在Action获取提交的表单数据方法总结

有Index视图如下:


视图代码如下:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    主页
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
    <br />
    <br />

    <% using(Html.BeginForm("HandleForm", "Home")) %>
    <% { %>
        Enter your name: <%= Html.TextBox("name") %>
        <br /><br />
        Select your favorite color:<br />
        <%= Html.RadioButton("favColor", "Blue", true) %> Blue <br />
        <%= Html.RadioButton("favColor", "Purple", false)%> Purple <br />
        <%= Html.RadioButton("favColor", "Red", false)%> Red <br />
        <%= Html.RadioButton("favColor", "Orange", false)%> Orange <br />
        <%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br />
        <%= Html.RadioButton("favColor", "Brown", false)%> Brown <br />
        <%= Html.RadioButton("favColor", "Green", false)%> Green 
        <br /><br />
        <%= Html.CheckBox("bookType") %> I read more fiction than non-fiction.<br />
        <br /><br />
        My favorite pet: <%= Html.DropDownList("pets") %>
        <br /><br />
        <input type="submit" value="Submit" />
    <% } %>

</asp:Content>

如图填写表单数据:

分别使用不同的表单处理方法,对提交的表单数据在视图FormResults呈现。

提交表单对应的HomeController,包含以不同方法获取表单数据的代码,如下:

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

namespace HtmlHelper.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "欢迎使用 ASP.NET MVC!";

            //手动构造页面中下拉框的宠物数据
            List<string> petList = new List<string>();
            petList.Add("Dog");
            petList.Add("Cat");
            petList.Add("Hamster");
            petList.Add("Parrot");
            petList.Add("Gold fish");
            petList.Add("Mountain lion");
            petList.Add("Elephant");

            ViewData["Pets"] = new SelectList(petList);

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        /// <summary>
        /// 处理表单提交数据,方法1:使用传统的Request请求取值
        /// </summary>
        /// <returns></returns>
        public ActionResult HandleForm()
        {
            ViewData["name"] = Request["name"];
            ViewData["favColor"] = Request["favColor"];
            ViewData["bookType"] = Request["bookType"];
            ViewData["pet"] = Request["pets"];

            return View("FormResults");
        }

        /// <summary>
        /// 处理表单提交数据,方法2:Action参数名与表单元素name值一一对应
        /// </summary>
        /// <param name="name"></param>
        /// <param name="favColor"></param>
        /// <param name="bookType"></param>
        /// <param name="pets"></param>
        /// <returns></returns>
        //public ActionResult HandleForm(string name, string favColor, Boolean bookType, string pets)
        //{
        //    ViewData["name"] = name;
        //    ViewData["favColor"] = favColor;
        //    ViewData["bookType"] = bookType;
        //    ViewData["pet"] = pets;

        //    return View("FormResults");
        //}

        /// <summary>
        /// 处理表单提交数据,方法3:从MVC封装的FormCollection容器中读取
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        //public ActionResult HandleForm(FormCollection form)
        //{
        //    ViewData["name"] = form["name"];
        //    ViewData["favColor"] = form["favColor"];
        //    ViewData["bookType"] = form["bookType"];
        //    ViewData["pet"] = form["pets"];

        //    return View("FormResults");
        //}

        /// <summary>
        /// 处理表单提交数据,方法4:使用实体作为Action参数传入,前提是提交的表单元素名称与实体属性名称一一对应
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //[HttpPost]
        //public ActionResult HandleForm(InforModel infor)
        //{
        //    ViewData["name"] = infor.name;
        //    ViewData["favColor"] = infor.favColor;
        //    ViewData["bookType"] = infor.bookType;
        //    ViewData["pet"] = infor.pets;

        //    return View("FormResults");
        //}

    }
}

在FormResults视图显示ViewData的数据,如图所示:


  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ASP.NET MVC 添加数据,你需要遵循以下步骤: 1. 创建一个模型类,定义你要添加的数据的属性,例如: ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } ``` 2. 创建一个控制器类,并添加一个方法来处理添加数据的请求,例如: ```csharp public class ProductsController : Controller { private readonly ApplicationDbContext _context; public ProductsController(ApplicationDbContext context) { _context = context; } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(Product product) { if (ModelState.IsValid) { _context.Add(product); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(product); } } ``` 3. 创建一个视图来显示添加数据表单,例如: ```html @model Product <form asp-action="Create"> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Price" class="control-label"></label> <input asp-for="Price" class="form-control" /> <span asp-validation-for="Price" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> ``` 4. 添加路由,以便能够从浏览器访问到添加数据的页面,例如: ```csharp app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "create", pattern: "products/create", defaults: new { controller = "Products", action = "Create" }); }); ``` 现在你可以通过访问 /products/create 来打开添加数据的页面,在表单输入数据提交数据将会被添加到数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值