【问题标题】:Generating a radio button list in MVC5在 MVC5 中生成单选按钮列表
【发布时间】:2017-06-08 17:23:54
【问题描述】:

我有必要的视图模型来为给定用户生成可用地址列表。
我也可以按照我的意图显示结构中的地址。

@if (Model.Addresses.Any())
{
    <ul class="ol">
        @foreach (var address in Model.Addresses)
        {
            <li>
                @{ Html.RenderPartial("_Address", address); }
            </li>
        }
    </ul>
}

我计划为这些地址中的每一个添加一个单选按钮前缀。

我正在渲染的模型给了我一个id。 ( 123456)

因此,每个项目的单选按钮应该具有这些属性,如下例所示 -

<input type="radio" id="addressId_123456" name="addressId" value="123456"/>

我该如何做到这一点?

【问题讨论】:

  • 您在这里使用部分是否有特殊原因?为什么不在循环中使用RadioButtonFor()
  • 这个相同的地址视图...将在不同型号的同一页面的不同部分重复。比如帐单地址和送货地址等。
  • 那么您应该使用EditorTemplate,而不是部分(以便您获得正确的名称属性进行绑定)。视图中的模型是否有属性addressId 用于绑定到选定的值?您希望在视图中显示的 Address 模型的其他属性是什么
  • 你不能简单地把 RadioButtonFor 放在部分里面吗?您需要制作 RadioButtonFor 的帮助吗?
  • @StephenMuecke 是的,该模型确实具有属性 addressId,而我需要的其他属性是 Name、Address1、Address2、State、PostalCode .... 我确实可以在视图中显示.问题只是如何在这些地址前面加上一个单选按钮,每个按钮都带有问题中提出的 id 和 value。

标签: c# html .net asp.net-mvc asp.net-mvc-5


【解决方案1】:

如果您正在寻找 RadioButtonFor,这里是带有引导程序的 HTML 帮助程序的代码。感谢@PaulDSheriff

#region Bootstrap/HTML 5 Radio Button
    /// <summary>
    /// Bootstrap and HTML 5 Radio Button.
    /// </summary>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="expression">An expression that identifies the object that contains the properties to render.</param>
    /// <param name="id">The 'id' attribute name to set.</param>
    /// <param name="name">The 'name' attribute to set.</param>
    /// <param name="text">The text to display next to this radio button.</param>
    /// <param name="value">The 'value' attribute to set.</param>
    /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param>
    /// <returns>An HTML radio button with the appropriate type set.</returns>
    public static MvcHtmlString RadioButtonBootstrapFor<TModel, TValue>(
          this HtmlHelper<TModel> htmlHelper,
          Expression<Func<TModel, TValue>> expression,
          string id,
          string name,
          string text,
          string value,
          object htmlAttributes = null)
    {
      return RadioButtonBootstrapFor(htmlHelper, expression, id, name, text, value, false, false, false, htmlAttributes);
    }

    /// <summary>
    /// Bootstrap and HTML 5 Radio Button in a Button Helper.
    /// This helper assumes you have added the appropriate CSS to style this radio button.
    /// </summary>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="expression">An expression that identifies the object that contains the properties to render.</param>
    /// <param name="id">The 'id' attribute name to set.</param>
    /// <param name="name">The 'name' attribute to set.</param>
    /// <param name="text">The text to display next to this radio button.</param>
    /// <param name="value">The 'value' attribute to set.</param>
    /// <param name="isChecked">Whether or not to set the 'checked' attribute on this radio button.</param>
    /// <param name="isAutoFocus">Whether or not to set the 'autofocus' attribute on this radio button.</param>
    /// <param name="useInline">Whether or not to use 'radio-inline' for the Bootstrap class.</param>
    /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param>
    /// <returns>An HTML radio button with the appropriate type set.</returns>
    public static MvcHtmlString RadioButtonBootstrapFor<TModel, TValue>(
      this HtmlHelper<TModel> htmlHelper,
      Expression<Func<TModel, TValue>> expression,
      string id,
      string name,
      string text,
      string value,
      bool isChecked,
      bool isAutoFocus,
      bool useInline = false,
      object htmlAttributes = null)
    {
      StringBuilder sb = new StringBuilder(512);
      string htmlChecked = string.Empty;
      string htmlAutoFocus = string.Empty;
      string rdoClass = "radio";

      if (isChecked)
      {
        htmlChecked = "checked='checked'";
      }
      if (isAutoFocus)
      {
        htmlAutoFocus = "autofocus='autofocus'";
      }
      if (useInline)
      {
        rdoClass = "radio-inline";
      }

      // Build the Radio Button
      sb.AppendFormat("<div class='{0}'>", rdoClass);
      sb.Append("  <label>");
      sb.AppendFormat("    <input id='{0}' name='{1}' type='radio' value='{2}' {3} {4} {5} />", 
                      id, name, value, htmlChecked, htmlAutoFocus, 
                      GetHtmlAttributes(htmlAttributes));
      sb.AppendFormat("    {0}", text);
      sb.Append("  </label>");
      sb.Append("</div>");

      // Return an MVC HTML String
      return MvcHtmlString.Create(sb.ToString());
    }
    #endregion

现在您看到 id、name 和 value 是参数。直接传递它们,如果您需要其他 html 属性,请将它们作为最终参数传递。 希望对您有所帮助

【讨论】:

  • 一个糟糕的解决方案,它甚至不使用正确的 2 路模型绑定并且没有客户端验证 - 这表明不了解 HtmlHelper 方法的工作原理(并且它没有解决问题)
  • @StephenMuecke,一旦你有了 id,你就可以发送值,它会正确生成输入 type="radio",请你先解释一下为什么这个扩展方法不能正常工作? HtmlHelpers 生成一个预定义的代码,例如 Html.Raw 会返回一个新的 HtmlString(value)。第二个示例 Html.LabelFor 与元数据一起创建了一个 TagBuilder,最后调用 tagBuilder.ToMvcHtmlString。你的观点是什么?是不是用 Helper 方法生成正确的 html?
  • 在评论中解释的原因有很多。这不会在任何地方使用来自ModelState(如果它们存在)的值来进行正确的 2-way 模型绑定。现在在哪里生成客户端验证所需的data-val-* 属性。
  • 我不同意第二点,data-val- 属性可以是最后一个参数的一部分,但它可以作为助手的一部分在内部处理,你是对的第一点。但是使用这些方法你仍然可以生成上面的 html
  • 那你也不明白如何创建扩展方法。如果您想编写自己的源代码,我建议您开始研究源代码。该代码中的所有内容都可以使用一行代码简单地正确完成 - @Html.DropDownListFor(m =&gt; m.someProperty, someValue, new { ... })
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-01
  • 2013-07-11
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多