Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC Generic Partial View Pattern
    text
    copied!<p>I have a partial view that I want to be generic. According to <a href="https://stackoverflow.com/questions/875085/generic-partial-view-how-to-set-a-generic-class-as-model">this question</a>, partial views cannot be generic. So I instead made an HtmlHelper extension that handles the pieces for which I want type-safety, then hands off the rest to a real partial view.</p> <p>Usually my helper is called on page load, which works fine, but sometimes I want to add a row or something through AJAX. When this happens, the controller cannot use my "partial view" since it does not have access to the HtmlHelper.</p> <p>Apart from having a partial view with a model of type <code>object</code>, is there anything I can do? </p> <p>I'm using Razor, if that is important.</p> <p>A simplified version of what I'm doing:</p> <pre><code>public static MvcHtmlString DoStuff&lt;T&gt;(this HtmlHelper html, IEnumerable&lt;T&gt; data, Func&lt;T, ViewModelType&gt; StronglyTypedFn, string PartialName) { // the pre- and post-processing for the partial view is complex enough I'd like // to encapsulate it. But I want the encapsulation to include the safety // benefits that generics give. var mappedData = data.Select(StronglyTypedFn); string htmlData = ""; foreach(var model in mappedData){ htmlData += html.Partial(PartialName, model); } htmlData += "some boilerplate footer html"; return htmlData; } </code></pre> <p>I realize that in this example I have so few lines of code outside the partial view that it seems pointless to have a helper, but in my real example it is more complex.</p> <p>Now, in an ajax call I want to return <code>Html.DoStuff()</code>. But I can't, because this requires access to the HtmlHelper, and the helper isn't available inside a controller.</p>
 

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