【问题标题】:Checkbox as a Link in ASP.net MVC 4 or 5复选框作为 ASP.net MVC 4 或 5 中的链接
【发布时间】:2015-05-27 16:08:21
【问题描述】:

是否可以在 ASP.net MVC 4 或 5 中将复选框作为参数链接来引用控制器的 AcionResult?

【问题讨论】:

  • 也许你可以用 JavaScript 做到这一点,但请提供更多信息你正在尝试做什么并分享一些代码。

标签: c# asp.net-mvc-4 checkbox asp.net-mvc-5


【解决方案1】:

是的,您可以通过制作自定义 html 助手来做到这一点。 在自定义助手中,你可以做任何你想做的事情

示例:

       public static MvcHtmlString CheckBoxLabelFor<TModel>(this HtmlHelper<TModel> pHtml, Expression<Func<TModel, bool>> pExpression, IDictionary<string, Object> pLabelHtmlAttributes, string pCaption)
    {
        try
        {
            MvcHtmlString tCheckBox;
            string tCheckBoxWithLabel;
            TagBuilder tBuilder;

            tCheckBox = InputExtensions.CheckBoxFor(pHtml, pExpression);
            tBuilder = new TagBuilder("label");
            tBuilder.MergeAttributes(new RouteValueDictionary(pLabelHtmlAttributes));

            tCheckBoxWithLabel ="<a>" + tBuilder.ToString(TagRenderMode.StartTag) + tCheckBox.ToString() + pCaption + "</label></a>";

            return MvcHtmlString.Create(tCheckBoxWithLabel);
        }
        catch (Exception ex)
        {
            clsINFEventLogger.LogEvent(mdlEnumerations.INFEventTypes.Error, ex.Message, ex.StackTrace);
            return null;
        }

    }

此代码使带有标签的复选框作为链接,现在要使用它并将链接重定向到动作控制器,您必须在视图上使用它,如下所示:

 @Html.CheckBoxLabelFor(model => model.Test,new Dictionary<string, object> {  { "onclick", "location.href= '" + @Url.Action(YourController, YourAction, Model) + "'" } }, "Test Caption")

您生成的 html 将如下所示:

<a><label onclick="location.href= '/Namespace/YourController/YourAction'"><input id="Test" name="Test" type="checkbox" value="true">Test</label></a>

您可以根据需要编辑自定义助手:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 2011-06-16
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2011-02-19
    • 2019-02-14
    相关资源
    最近更新 更多