Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable/hide a Partial View based on IList values?

I want to disable or hide a PartialView based on values inside two different ILists. Both of these lists are stored in two Session variables, _UserRoleList and _PartialRoleList.

The list contents of _UserRoleList are of type User which contains the following properties:

  • UserName
  • RoleID
  • RoleDescription
  • SID

The list contents of _PartialRoleList are of type PartialRole which contains the following properties:

  • PartialName
  • RoleID
  • AccessLevelID
  • AccessLevelDescription

Case 1 - Disable all input controls inside the Partial View:

Disable ALL input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") if a RoleID of 3 is found in both session lists.

Case 2 - Set all input controls to read-only inside the Partial View:

All input controls (textboxes, listboxes, checkboxes, dropdownlists) on the specified PartialView (with an id of "frmClientDetails") should have their read-only attribute set to true if aRoleID of 2 is found in both session lists.

Question: Would it be better to retrieve the two lists and then use a jQuery .each to loop through and search for equality on the RoleID fields? Would another option be to use Razor? If pseudo code could be provided, that would be a great help.

Controller snippet:

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();
}

Original 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)
}

Partial View - 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>
}
like image 766
Sean Avatar asked Dec 21 '25 22:12

Sean


1 Answers

Since disabled controls will not post back, its pointless to generate all that extra html, and since readonly controls cannot be edited, again it seems pointless to generate all that extra html and then send it all back unchanged to the server when you submit your form.

A better approach, performance wise would be to have 2 partial views (say) _ClientDetails.cshtml and _ReadOnlyClientDetails.cshtml. The first would contain your form and its editable controls and submit button, and the second would contain only the text values of your properties, for example

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

Then in your controller method that generates you main view, set a view model property (or ViewBag property) to indicate which partial to display, for example

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

and in the main view

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

Side note: Everything between you first @{ ... } except ViewBag.Title = "Client Details"; belongs in the controller method, not the view. And to do something like viewModel.Client = Model; makes no sense at all. Your view should be @model InvoiceCreditNoteViewModel and since you're not passing a model to the view, then viewModel.Client = Model; would not make sense anyway since its always null.

Its also not clear why your using Session. The code in your controller should be something like

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;
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!