You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET MVC5+EF同一视图中实现表单新增与数据表格展示

在ASP.NET MVC5 + Entity Framework中实现表单与数据表格同页展示

以下是具体实现步骤,包含完整代码示例:

1. 创建实体模型

定义包含Name和City字段的用户模型:

public class User
{
    public int Id { get; set; } // EF自动识别为主键
    public string Name { get; set; }
    public string City { get; set; }
}

2. 配置DbContext

创建数据库上下文类,用于EF的数据库操作:

public class AppDbContext : DbContext
{
    public AppDbContext() : base("DefaultConnection") // 对应Web.config中的连接字符串名称
    {
    }

    public DbSet<User> Users { get; set; }
}

在Web.config中添加数据库连接字符串(若不存在):

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=UserDb;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

3. 编写控制器逻辑

创建控制器处理页面加载和表单提交:

public class HomeController : Controller
{
    private readonly AppDbContext _dbContext = new AppDbContext();

    // GET请求:加载表单和用户列表
    public ActionResult Index()
    {
        var users = _dbContext.Users.ToList();
        return View(users);
    }

    // POST请求:处理表单提交
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(User user)
    {
        if (ModelState.IsValid)
        {
            _dbContext.Users.Add(user);
            _dbContext.SaveChanges();
            return RedirectToAction("Index"); // 重定向避免重复提交
        }
        // 验证失败时重新加载列表并返回视图
        var users = _dbContext.Users.ToList();
        return View(users);
    }
}

4. 编写视图(Index.cshtml)

在同一视图中同时渲染表单和数据表格:

@model List<User>

@{
    ViewBag.Title = "用户管理";
}

<h2>添加新用户</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.Label("姓名", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.Editor("Name", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessage("Name", "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.Label("城市", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.Editor("City", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessage("City", "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="添加" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<h2>用户列表</h2>
<table class="table">
    <tr>
        <th>姓名</th>
        <th>城市</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>@item.Name</td>
        <td>@item.City</td>
    </tr>
}
</table>

关键说明

  • 视图使用List<User>作为模型,同时承载用户列表数据和表单绑定的字段匹配需求。
  • 采用PRG(Post/Redirect/Get)模式,提交后重定向回Index页面,避免用户刷新导致重复提交。
  • 内置的验证标签会自动处理客户端和服务端的合法性校验,确保输入数据有效。

内容的提问来源于stack exchange,提问作者naresh nagaraj1996

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 02:37:24