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

ASP.NET MVC视图条件展示:点击提交后才显示表格内容

当然可行啦!这个需求很常见,咱们只需要加个简单的状态判断,就能控制表格只在提交后才显示。下面是具体的实现步骤和修改后的代码:

解决方案

1. 添加提交状态标识(两种可选方式)

方式一:给模型新增属性

你可以在Employee模型里加一个布尔属性,用来标记表单是否已经提交:

public class Employee
{
    // 你已有的属性
    public int Service_Code { get; set; }
    public string Service_Name { get; set; }
    public List<Employee> data { get; set; }
    public SelectList ser_code { get; set; }
    
    // 新增:标记是否已提交表单
    public bool IsSubmitted { get; set; }
}

方式二:使用ViewBag(无需修改模型)

如果不想改动模型,也可以用ViewBag来传递提交状态,这种方式更轻量化。

2. 修改控制器的提交方法

在TestController的save方法里,处理完数据查询后,设置提交状态:

[HttpPost]
public ActionResult save(Employee model)
{
    // 这里写你的业务逻辑:比如根据查询条件获取model.data的数据
    
    // 方式一:设置模型的提交状态
    model.IsSubmitted = true;
    
    // 方式二:如果用ViewBag的话,替换成下面这行
    // ViewBag.Submitted = true;
    
    return View("menu", model);
}

3. 修改视图代码,控制表格显示

原视图里表格是默认渲染的,我们需要加个判断,让它只在提交后才显示:

@model mvclearn.Models.Employee
@{ ViewBag.Title = "menu"; }
@{ Layout = null; }
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<style>
.error { color: red; }
</style>
<div class="container">
<div class="container"style="width:30%">
@using (Html.BeginForm("save", "Test", FormMethod.Post))
{
    @Html.DropDownListFor(m => m.Service_Code, Model.ser_code, "--select--", new { @class = "form-control", @placeholder = "Enter Service code" })
    @Html.ValidationMessageFor(m => m.Service_Code, "", new { @class = "error" })
    @Html.TextBoxFor(m => m.Service_Name, new { @class = "form-control", @placeholder = "Service Name" })
    @Html.ValidationMessageFor(m => m.Service_Name, "", new { @class = "error" })
    <input type="submit" value="submit" class="btn-block" />
}

<!-- 核心:只有提交后才渲染表格区域 -->
@if (Model.IsSubmitted) <!-- 如果用ViewBag,就改成 @if (ViewBag.Submitted == true) -->
{
    <table class="table">
        @{ 
            if (Model.data != null && Model.data.Count() > 0)
            {
                <tr>
                    <th> @Html.DisplayName("Service_Code") </th>
                    <th> @Html.DisplayName("Service_Name") </th>
                </tr>
                foreach (mvclearn.Models.Employee item in Model.data)
                {
                    <tr>
                        <td> @item.Service_Code </td>
                        <td> @item.Service_Name </td>
                    </tr>
                }
            }
            else
            {
                <p>No records found</p>
            }
        }
    </table>
}
</div>
</div>

效果说明

  • 页面刚加载时,IsSubmitted默认是false(或者ViewBag.Submitted不存在),表格区域完全不会渲染;
  • 点击提交按钮后,控制器会把提交状态设为true,视图就会显示表格:如果data有数据就展示列表,没有就显示No records found。

这样就完美实现你的需求啦!

内容的提问来源于stack exchange,提问作者Pritesh Naik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:57:21