如何基于IList值禁用/隐藏局部视图

本文关键字:隐藏局 视图 何基于 IList | 更新日期: 2024-09-08 10:37:04

我想根据两个不同IList中的值禁用或隐藏PartialView。这两个列表都存储在两个会话变量_UserRoleList_PartialRoleList中。

_UserRoleList的列表内容属于User类型,包含以下属性:

  • 用户名
  • 角色ID
  • 角色描述
  • SID

_PartialRoleList的列表内容属于PartialRole类型,包含以下属性:

  • PartialName
  • 角色ID
  • AccessLevelID
  • AccessLevelDescription

情况1-禁用部分视图内的所有输入控件:

如果在两个会话列表中都找到3RoleID,则禁用指定PartialView(id为"frmClientDetails")上的ALL输入控件(文本框、列表框、复选框、下拉列表)。

情况2-在部分视图中将所有输入控件设置为只读:

如果在两个会话列表中都找到2RoleID,则指定PartialView(id为"frmClientDetails")上的所有输入控件(文本框、列表框、复选框、下拉列表)的只读属性都应设置为true。

问题:检索这两个列表,然后使用jQuery .each循环并搜索RoleID字段上的相等性,会更好吗?另一种选择是使用Razor吗?如果可以提供伪代码,那将是一个很大的帮助。

控制器片段

public ViewResult Index()   /* Master View, starting point of application */
{
    int userID;
    IList<User> userRoleList;
    IList<PartialRole> partialRoleList;
    WindowsIdentity identity = null;
    identity = WindowsIdentity.GetCurrent();
    userRoleList = _homeService.GetUserDetails(identity.User.ToString());
    userID = userRoleList.First().ID;
    partialRoleList = _homeService.GetPartialDetails(userID);
    if (Session["_UserRoleList"] == null)
    {
        HttpContext.Session.Contents.Add("_UserRoleList", userRoleList);
    }
    if (Session["_PartialRoleList"] == null)
    {
        HttpContext.Session.Contents.Add("_PartialRoleList", partialRoleList);
    }
    return View();
}

原始视图-ClientDetails.cshtml

@using InvoiceManagement.Models
@model InvoiceClient
@{
InvoiceCreditNoteViewModel viewModel = new InvoiceCreditNoteViewModel();
viewModel.Client = Model;
ViewBag.Title = "Client Details";
 List<User> userRoleList = Session["_UserRoleList"] != null ? (List<User>)Session["_UserRoleList"] : null;
 List<PartialRole> partialRoleList = Session["_PartialRoleList"] != null ? (List<PartialRole>)Session["_PartialRoleList"] : null;
}
@section scripts{
<script type="text/javascript">
    $(document).ready(function () {
        $('input[type=radio][name=optionInvoiceCreditNote]').change(function () {
            if (this.value == 'invoice') {
                $("#InvoiceGrid").show();
                $("#CreditNoteGrid").hide();
            }
            else if (this.value == 'creditNote') {
                $("#InvoiceGrid").hide();
                $("#CreditNoteGrid").show();
            }
        });
        $('#showActive').click(function (e) {
            if($(this).prop('checked') === true){
                var url = '@Url.Action("FilterActiveOnlyAgreements")';
                $.get(url, { invoiceClientID: '@Model.ID' }, function (result) {
                    $('#agreementGrid').html(result);
                });
            }
            else {
                var url = '@Url.Action("FilterAllAgreements")';
                $.get(url, { invoiceClientID: '@Model.ID' }, function (result) {
                    $('#agreementGrid').html(result);
                });
            }
        });
    });
</script>
}
@Html.Partial("ClientDetailsFormPartial", viewModel.Client)
@if (viewModel.Client.ID > 0)
{
    @Html.Partial("ClientDetailsAgreementPartial")
    @Html.Partial("InvoiceCreditNoteContainerPartial", viewModel)
}

部分视图-ClientDetailsFormPartial

@using InvoiceManagement.Models
@model InvoiceClient
@using (@Html.BeginForm("ClientDetails", "Client", FormMethod.Post, new { @id = "frmClientDetails" }))
{
    <div class="container-fluid">
        <div class="row">
            <div class="col-xs-2">
                <h2>Client Details</h2>
            </div>
            <div class="col-xs-2" style="min-height: 70px;">
                <a href="/client/SearchForClient" class="btn btn-default" style="position: absolute; bottom: 15px">Search New Client</a>
            </div>
            <div class="form-group col-xs-2" style="min-height: 70px;">
                <div class="input-group" style="top: 21px">
                    <span class="input-group-addon" id="client-ID">Client ID</span>
                    @Html.TextBox("ID", Model.ID, new { @class = "form-control", @readonly = "readonly" })
                </div>
                <div class="has-error">
                    @Html.ValidationMessageFor(m => m.ID, String.Empty, new { @class = "help-block" })
                </div>
            </div>
            <div class="form-group col-xs-3" style="min-height: 70px;">
                <div class="input-group" style="top: 21px">
                    <span class="input-group-addon" id="accounting-ID">Accounting ID</span>
                    @if (Model.AID == null && Model.ID == 0)
                    {
                        @Html.TextBoxFor(m => m.AID, new { @class = "form-control" }) }
                    else
                    {
                        @Html.TextBoxFor(m => m.AID, new { @class = "form-control", @readonly = "readonly" }) }
                </div>
            </div>
            <div style="padding-top: 22px;">
                <div class="has-error">
                    @Html.ValidationMessageFor(m => m.AID, String.Empty, new { @class = "help-block" })
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-xs-7">
                <div class="input-group">
                    <span class="input-group-addon" id="client-name">Client Name</span>
                    @Html.TextBoxFor(m => m.InvoiceClientName, new { @class = "form-control", @name = "InvoiceClientName" })
                </div>
                <div class="has-error">
                    @Html.ValidationMessageFor(m => m.InvoiceClientName, String.Empty, new { @class = "help-block" })
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-xs-3">
                <div class="input-group">
                    <span class="input-group-addon" id="default-tax-code-1">Default Tax Code 1</span>
                    @Html.DropDownListFor(m => m.DefaultTaxCodeID1, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode1, new { @class = "form-control", @id = "default-tax-code1-ID", @name = "defaultTaxCodeID1" })
                </div>
            </div>
            <div class="form-group col-xs-3 col-xs-offset-1">
                <div class="input-group">
                    <span class="input-group-addon" id="default-tax-code-2">Default Tax Code 2</span>
                    @Html.DropDownListFor(m => m.DefaultTaxCodeID2, (IEnumerable<SelectListItem>)ViewBag.PopulateDefaultTaxCode2, new { @class = "form-control", @id = "default-tax-code2-ID", @name = "defaultTaxCodeID2" })
                </div>
            </div>
        </div>
        <div class="row">
            <div class="form-group col-xs-3">
                <div class="input-group">
                    <span class="input-group-addon" id="status">Status</span>
                    @Html.DropDownListFor(m => m.StatusID, (IEnumerable<SelectListItem>)ViewBag.PopulateStatus, new { @class = "form-control", @id = "status-ID", @name = "statusID" })
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xs-2 col-xs-offset-7">
                @if (Model == null || Model.ID == 0)
                {
                    <button type="submit" class="btn btn-default">Add New Client</button>
                }
                else
                {
                    <button type="submit" class="btn btn-default">Update Existing Client</button>
                }
            </div>
        </div>
    </div>
}

如何基于IList值禁用/隐藏局部视图

由于disabled控件不会返回,因此生成所有多余的html是毫无意义的,并且由于readonly控件无法编辑,因此再次生成所有额外的html,然后在提交表单时将其原封不动地发送回服务器似乎也是毫无意义的。

从性能角度来看,更好的方法是有两个局部视图(比如_ClientDetails.cshtml_ReadOnlyClientDetails.cshtml)。第一个包含表单及其可编辑控件和提交按钮,第二个只包含属性的文本值,例如

@Html.DisplayNameFor(m => m.InvoiceClientName)
@Html.DisplayFor(m => m.InvoiceClientName)

然后,在生成主视图的控制器方法中,设置视图模型属性(或ViewBag属性)以指示要显示的部分,例如

ViewBag.IsReadonly = true; // or omit depending on your logic

在主视图中为

@if(ViewBag.IsReadonly)
{
    @Html.Partial("_ReadOnlyClientDetails", viewModel.Client)
}
else
{
    @Html.Partial("_ClientDetails", viewModel.Client)
}

旁注:除了ViewBag.Title = "Client Details";之外,您第一个@{ ... }之间的所有内容都属于控制器方法,而不是视图。做viewModel.Client = Model;这样的事情毫无意义。您的视图应该是@model InvoiceCreditNoteViewModel,因为您没有将模型传递给视图,所以viewModel.Client = Model;无论如何都没有意义,因为它总是null

也不清楚你为什么使用Session。控制器中的代码应该类似

IList<User> userRoleList = _homeService.GetUserDetails(identity.User.ToString());
int userID = userRoleList.First().ID;
IList<PartialRole> partialRoleList = _homeService.GetPartialDetails(userID)
List<int> values = new List<int>(){ 2, 3 };
if (userRoleList.Any(x => values.Contains(x.RoleID)) && partialRoleList.Any(x => values.Contains(x.RoleID)))
{
    ViewBag.IsReadonly = true;
}