How do I redirect JavaScript in ASP.Net MVC?

The following code will create a link to the page I want to go to.

<%= Html.ActionLink(image.Title, image.Id.ToString(), "Image") %> 

The following code will display the correct URL on the page.

 <%= Url.Action("Index", "Image", new { id = image.Id })%> 

But when I try to use it in javascript, it fails. (with some weird error about page inheritance)

 <div onclick="window.location = '<%= Url.Action("Index", "Image", new { id = image.Id })%>'"> ... </div> 

Should the above code work? What is the correct way to create javascript undertaken above?

Refresh . Error:

Views \ Home \ Index.aspx.cs (9): ASPNET error: make sure that the class defined in this code file matches the "inherits" attribute and that it extends the correct base class (for example, Page or UserControl).

This seems to indicate a big problem.

Fixed Thanks for your help, the code contains a div with runat="server" . When I remove this, it works fine. This may be because there is no form with runat="server" , but I would expect another error for this.

Since this question does not seem significant, should it be deleted?

+3
source share
3 answers

This should actually work. ASP.NET MVC will replace all <% = ...%> or similar tags, it will not recognize if it is an html definition or javascript. What is the result of your submission? Is the "weird bug" from Javascript or ASP.NET?

EDIT : regarding your update: make sure your Index.aspx has a “Codebehind” attribute (this is in the page tag on the very first line) pointing to Index.aspx.cs and the “Inherits” attribute contains the class name of the Page / User-Control class in code.

+2
source

See this for a possible solution to your error message. Codebehind vs Codefile.

+1
source

Looks like you have a HomeController with the Image method correct? Then it should be

 <%= Url.Action("Image", "Home", new { id = image.Id })%> 
0
source

All Articles