开发者

MVC radio buttons disabled readonly when not authenticated

开发者 https://www.devze.com 2023-04-02 08:58 出处:网络
@Html.RadioButtonFor(modelItem => item.CheckerApproved, true) @Html.LabelFor(modelItem => item.CheckerApproved, \"Accepted\")
@Html.RadioButtonFor(modelItem => item.CheckerApproved, true)
@Html.LabelFor(modelItem => item.CheckerApproved, "Accepted")
@Html.RadioButtonFor(modelItem => item.CheckerApproved, false)
@Html.LabelFor(modelItem => item.CheckerApproved, "Rejected")

What I'm wanting is for some way to make these disabled or readonly when the user isn't Authenticated.

ie. Enabled when:

HttpContext.Current.User.Identity.IsAuthenticated

Is there an easy way to do this? Would you put them on some sort开发者_如何转开发 of panel? Not sure for MVC?

Would you set there enabledability individually for each line?


What I'm wanting is for some way to make these disabled or readonly when the user isn't Authenticated.

A more than excellent candidate for a custom helper:

using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class RadioExtensions // LOL for this name
{ 
    // TODO: Pick a better name here than MyRadioButtonFor
    public static IHtmlString MyRadioButtonFor<TModel, TProperty>(
        this HtmlHelper<TModel> html,
        Expression<Func<TModel, TProperty>> ex,
        object value
    )
    {
        var isAuthenticated = html.ViewContext.HttpContext.User.Identity.IsAuthenticated;
        if (isAuthenticated)
        {
            return html.RadioButtonFor(ex, value);
        }
        // Remark: adapt with readonly if necessary,
        // note that there is a crucial difference between a readonly and disabled
        // element in HTML. Up to you to pick the desired behavior
        return html.RadioButtonFor(ex, value, new { @disabled = "disabled" });
    }
}

and in your view simply consume the fruits of your labour:

@Html.MyRadioButtonFor(modelItem => item.CheckerApproved, true)
@Html.LabelFor(modelItem => item.CheckerApproved, "Accepted")
@Html.MyRadioButtonFor(modelItem => item.CheckerApproved, false)
@Html.LabelFor(modelItem => item.CheckerApproved, "Rejected")
0

精彩评论

暂无评论...
验证码 换一张
取 消