Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC3 Razor Extension: Returning two controls
    primarykey
    data
    text
    <p>I am trying to create an extension that renders a read-only drop down list. It appears that just slapping a <code>readonly="true"</code> attribute on the <code>&lt;select&gt;</code> element does not work, so I would like to render a disabled <code>&lt;select&gt;</code> element and a hidden input.</p> <p>Here's the code I have so far:</p> <pre><code>public static MvcHtmlString DropDownListFor&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, IEnumerable&lt;SelectListItem&gt; selectList, object htmlAttributes, bool isReadonly) { var values = new RouteValueDictionary(htmlAttributes); if (isReadonly) values["disabled"] = "disabled"; var select = htmlHelper.DropDownListFor&lt;TModel, TProperty&gt;(expression, selectList, values); var hiddenField = htmlHelper.HiddenFor&lt;TModel, TProperty&gt;(expression); var bothFields = ?; return bothFields; } </code></pre> <p><b>What is the right way to render out multiple controls from a Razor extension?</b></p> <p><em><strong>Edited: Solution</em></strong></p> <p>Figured it out. Evidently you can just call <code>ToString()</code> on two elements and return that. As Jerad pointed out, the <code>&lt;select&gt;</code>'s id must be modified so it's not the same as the id of the hidden input. My final code looks like this:</p> <pre><code>public static MvcHtmlString DropDownListFor&lt;TModel, TProperty&gt;( this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, IEnumerable&lt;SelectListItem&gt; selectList, object htmlAttributes, bool isReadonly) { if (isReadonly) { var values = new RouteValueDictionary(htmlAttributes); values["disabled"] = "disabled"; values["id"] = (expression.Body as MemberExpression).Member.Name + "_Disabled"; var select = htmlHelper.DropDownListFor&lt;TModel, TProperty&gt;(expression, selectList, values); var hiddenField = htmlHelper.HiddenFor&lt;TModel, TProperty&gt;(expression); return new MvcHtmlString(select.ToString() + hiddenField.ToString()); } else { return htmlHelper.DropDownListFor&lt;TModel, TProperty&gt;(expression, selectList, htmlAttributes); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload