如何通过MVC操作方法显示/隐藏HTML按钮

How to show/hide HTML Buttons via MVC Action Method

本文关键字:隐藏 HTML 按钮 显示 何通过 MVC 操作方法      更新时间:2023-09-26

在我的网页中,我需要根据名为ButtonType的参数值填充按钮。
假设ButtonType == "Edit",那么我需要隐藏每个按钮,但butUpdate.

我想知道如何通过MVC操作方法显示/隐藏html按钮。

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult SupplierDetail(int SupplierID, string ButtonType)
    {   
        var Supplier = supplierListRepository.Supplier_SelectByID(SupplierID);
        return View(Supplier);
    }

我正在使用 Asp.net Mvc 剃刀形式。

@using (Html.BeginForm("SupplierDetail_SubmitClick", "Supplier", FormMethod.Post, new { id = "frmSupplierDetail" }))
{   
@Html.ValidationSummary(true)
<table cellpadding="0" cellspacing="0" border="0" style="width:450px; height:auto">
.....
<tr>
    <td>@Html.LabelFor(model => model.Phone)</td>
    <td>@Html.EditorFor(model => model.Phone)
        @Html.ValidationMessageFor(model => model.Phone)</td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>
<tr>
    <td>&nbsp;</td>
    <td>
        <input type="submit" id="butSave" name="butSave" value="Save" style="width:100px; height:auto" />
        <input type="submit" id="butUpdate" name="butUpdate" value="Update" style="width:100px; height:auto" />
        <input type="submit" id="butDelete" name="butDelete" value="Delete" style="width:100px; height:auto" />
        <input type="submit" id="butReset" name="butReset" value="Reset" style="width:100px; height:auto" />
    </td>
</tr>
</table>
</div>
<div id="content">
@Html.ActionLink("Back to List", "Index")
</div>
}

每个建议将不胜感激。

显示/隐藏按钮不是控制器操作的责任。控制器操作甚至不知道/不应该知道按钮的含义。这是存在于视图上的概念。另一方面,控制器操作应该与模型通信并准备一个视图模型,该模型传递给视图进行显示。因此,您可以定义一个视图模型,该模型将包含定义按钮可见性的属性,并根据 ButtonType 参数的值相应地设置这些属性。然后,控制器操作将此视图模型 pas 到视图,而不是您当前传递的supplier对象。显然,视图模型也将具有容纳该供应商的属性。现在,留给视图的只是基于视图模型属性的值来决定如何显示按钮。

控制器中的

将按钮类型添加到视图数据:

ViewData["ButtonType"] = ButtonType

然后,在视图本身中,您可以添加 if/else 语句或适合所有情况的任何其他逻辑,以决定要呈现的内容:

@if (ViewData["ButtonType"].ToString() == "Edit")
{
    <input type="submit" id="butUpdate" name="butUpdate" value="Update"    
     style="width:100px; height:auto" />      
}

当然,这只是可以做什么的演示,Yuo 应该使代码适应您的业务逻辑