MVC Razor helper does not exist in current context

2019-07-21 11:21发布

问题:

I have created a custom razor helper in my MVC4 Web application that I need to be usable in all of my views.

In all of my view pages, I can't seem to use my custom helper. VS2012 doesn't just see it.

How Can I resolve this please ?

EDIT: It actually works when I run the page, it's just VS that doesn't see it.

Here is my helper which is located in Helpers.cshtml within my AppCode folder.

@helper TextBox(string title, string id, string placeholder, bool required){    
<ul>
    <li>
        <label for="@id">@title</label>
    </li>
    <li>
        <input type="text" name="this" class="@if (@required) {<text>required</text>}" minlength="2" id="@id" placeholder="@placeholder" />
    </li>
</ul>
}

回答1:

If it is razor helper(using @helper syntax), you should define it in view placed within \App_Code

We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a \App_Code directory that you create at the root of a project. For example, below I created a “ScottGu.cshtml” file within the \App_Code folder, and defined two separate helper methods within the file (you can have any number of helper methods within each file):

And if it is more traditional html helper, you should reference it, by adding record to namespaces element of <system.web.webPages.razor> defined in ~\Views\Web.Config. If you want to use it only in singe view, you could add @using directive on top of view.



回答2:

Restart Visual Studio

Clean and rebuild alone was not enough but the steps that worked for me were:

  1. Clean solution
  2. Restart Visual Studio (2012)
  3. Rebuild solution

After those steps, the Visual Studio Intellisense picked it up again.



回答3:

Try to build/rebuild the project (if your helper is in the App_Code folder).

Then VS will recognize the helper.



回答4:

In any view you could call your custom Razor helper like this:

@Helpers.TextBox("some title", "someid", "default value", false)

This assumes that your helper is defined inside ~/App_Code/Helpers.cshtml.