Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>So this is the line that is failing:</p> <pre><code>return (new UrlHelper(instance.htmlHelper.ViewContext.RequestContext)).Content(url); </code></pre> <p>We know that instance isn't null due to the line above that already checks for null. Null reference exceptions are the most common unhandled exceptions and are also the easiest to avoid. In general, you should never assume properties or parameters that are nullable types are not null. My guess is that instance.htmlHelper is your problem. I am assuming that htmlHelper is an instance of System.Web.Mvc.HtmlHelper. Therefore, ViewContext and RequestContext <em>should</em> not be null if that is a valid HtmlHelper created by MVC.</p> <p>The simple solution is to check for nulls like this:</p> <pre><code>if (instance.htmlHelper == null) { throw new InvalidOperationException("htmlHelper has not been populated."); } return (new UrlHelper(instance.htmlHelper.ViewContext.RequestContext)).Content(url); </code></pre> <p>Obviously you could repeat this for ViewContext and RequestContext by MVC should populate those.</p> <p>Now assuming htmlHelper is null (the most likely situation), you have a slight design problem here. What you should really be doing is extending the HtmlHelper class and not using a static method. Also, you seem to be using some kind of static instance which is probably also not valid in MVC. MVC <em>typically</em> instantiates controllers and views for each request. You can still use the static method for a web forms implementation, but for MVC you should extend HtmlHelper like this:</p> <pre><code>public static MvcHtmlString GenerateUrl(this htmlHelper, string url) { return (new UrlHelper(htmlHelper.ViewContext.RequestContext)).Content(url); } </code></pre> <p>Make sure you are always using the currently active HtmlHelper from MVC and not some static instance. I'm not sure off the top of my head if ViewContext or RequestContext could be null after a request has been completed. I've never tried to persist an HtmlHelper after one request. Even if they aren't null, they could otherwise be invalid and be causing your problem further down in the MVC pipeline.</p> <p>Hope that helps.</p>
    singulars
    1. This table or related slice is empty.
    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