Razor MVC4 Url.Action not working
Asked Answered
W

2

8

I have a code as below in razor view

<a href="@Url.Action("Details", "Mycontr", new {id =16}, Request.Url.Scheme)">

while I double click on this item it is redirected to below Url

http://localhost:49280/Mycontr/Section/@Url.Action(

But whereas the expected was

http://localhost:49280/Mycontr/Details/16

Below is RouteConfig

routes.MapRoute(
   name: "Capsule",
   url: "Mycontr/Details/{id}",
   defaults: new { controller = "Mycontr", action = "Details", id = UrlParameter.Optional }
 );
 routes.MapRoute(
   name: "Section",
   url: "Mycontr/Section/{id}",
   defaults: new { controller = "Mycontr", action = "Section", id = UrlParameter.Optional }
 );

Kindly suggest.

I narrowed down the issue. Html.Raw is causing issue. I have the code like

@Html.Raw(HttpUtility.HtmlDecode(Model.sContent)) 

the variable contains generated html that has Ur.Action. If I just place directly the html generated code in razor view without Html.Raw it is working fine. But if I take out Html.Raw the runtime generated html script that is displayed like

&lt;style type=&#39;text/css&#39;&gt;&lt;/style&gt;&lt;center&gt;&lt;div style=&quot;width:460px;&quot;&gt;&lt;div style=&quot;width: 460px; float: left;&quot;&gt;&lt;div s...

Is there a way that I can display html script in variable without using Html.Raw encoding? Half the issue got resolved by using HtmlString instead string variable for holding generated Html script, but the HtmlString couldn't decode @Url.Action syntax in the string.

Below is the latest code that I have been struggling to get it work. Please help.

                string templFile = string.Format("{0}\\DivTemplate.htm", path);
            HtmlDocument divDoc = new HtmlDocument();
            StreamReader sRdr = new StreamReader(templFile, Encoding.UTF8);
            divDoc.Load(sRdr);
            XmlNodeList divs = regions.ChildNodes;
            IEnumerator enmrDivs  = divs.GetEnumerator();
            while (enmrDivs.MoveNext())
            {
                XmlNode node = (XmlNode)enmrDivs.Current;
                string divId = node["DivId"].InnerText;
                string capId = node["CapsuleId"].InnerText;
                HtmlString sUrlAct = new HtmlString("@Url.Action(\"Capsule\", \"Publication\", new { id=\""+capId+"\" }))");
                //string sUrlAct = "@Url.Action(\"Capsule\", \"Publication\", new { id=\""+capId+"\"})";
                string divFile = string.Format("{0}\\{1}.htm", path, divId);

                HtmlDocument divRgnDoc = new HtmlDocument();
                StreamReader sR = new StreamReader(divFile, Encoding.UTF8);
                divRgnDoc.Load(sR);
                foreach (HtmlNode link in divRgnDoc.DocumentNode.SelectNodes("//a[@href]"))
                {
                    link.Attributes.RemoveAll();
                    link.Attributes.Add("href", sUrlAct.ToString());
                }
                HtmlNode divNode = divDoc.GetElementbyId(divId);
                divNode.AppendChild(divRgnDoc.DocumentNode.FirstChild.CloneNode(true));
                sR.Close();
            }

            sContent = new HtmlString (divDoc.DocumentNode.InnerHtml);
            sRdr.Close();
Westfalen answered 15/3, 2013 at 19:56 Comment(13)
Any reason not to use Html.ActionLink helper?Upstate
You may try to replace double quotes with single for href. Maybe double quotes in both html and C# code are confusing the rendering engine (Razor).Upstate
do you have ending </a> tag? an you post view code which wraps <a>Betancourt
@Upstate Yes, there is reason for not to use ActionLink as it will generate <a> tag that I want to avoid in my code, as in my code already has <a> tag followed up with content & ending with </a> tag. I use AgilityPack for html parsing, while I specify any attribute value through its usage it is adding double quotes for each value, not sure if there is way to let the parser avoid adding quotes to attribute valuesWestfalen
@Betancourt Yes, there is an ending </a> tag. The format I have is <a href=".." > some other content </a>Westfalen
@Naga, Floremin adviced to replace whole <a/> tag with ActionLink. Can you please show generated html, looks like you do some nasty staff with AgilityPack.Betancourt
@Dima, Below is the generated html code snipped <a href="@Url.Action("Details", "Mycontr", new { id="16" }, Request.Url.Scheme)">Dhanwin-FirstBirthday</a>&nbsp;<a href="@Url.Action("Details", "Mycontr", new { id="16" }, Request.Url.Scheme)">Dhanwin</a>Westfalen
@Floremin, I tried replacing double quotes with single quotes then issue remained sameWestfalen
It's your Razor view code, but i'm asking about html which is produced by this view. You may put it in your question, it will be more readable this way.Betancourt
after replacing with single quotes I could see that view engine is performing some background but it failed to redirect to the right action method, I think engine not recognizing the code in double quotes. Not sure why engine unable to pick the right action? Is there something I miss in RouteConfig?Westfalen
My issue is more close to linkWestfalen
ActionLink is more tedious task in my case, the code already generated <a tags, ActionLink will generate <a tags again that already exists in the html script. Replacing all <a tags with @ActionLink server script is little expensive thing. If I can make just the routing thing work with '@Url.Action' that will be end.Westfalen
why? why would you double-click a link?Holub
O
13

I know its bit late but I came across this post when I am searching for something.

Here in your code problem is with your anchor tag and the double quotes.

<a href="@Url.Action("Details", "Mycontr", new {id =16}, Request.Url.Scheme)">

You are technically telling the parser that you are referencing the hyperlink between "URL" (double quotes) that means href is @Url.Action(. You can do this way (use single quote to assign your href) and hope that works

<a href='@Url.Action("Details", "Mycontr", new {id =16}, Request.Url.Scheme)'>

now you href will be @Url.Action("Details", "Mycontr", new {id =16}, Request.Url.Scheme)

Overprize answered 17/8, 2013 at 9:50 Comment(2)
Thats right a double quote within double quote is misleading javascriptWestfalen
It might be a bit confusing to read, but using all double quotes is fine here. The @ prompts razor to switch to c# mode and it remains in c# mode until the closing round bracket. The inner double quotes will all be parsed as c#, by the time it is returned to the browser it will only have one pair of double quotes, containing a URL.Jer
W
-5

I have solved the issue. I really dont need @Url.Action to the href. I have just replaced the code to logical path as below

/Publication/Capsule/ + capId

this link helped me solve the issue. Thanks to Jorge saving days of work :)

Westfalen answered 17/3, 2013 at 8:16 Comment(4)
What if your site is not on the root level? For example, if the site is at /some/folder/Home/Index, a link to /Publication/Capsule/4 would not lead to your site.Ode
I have seen that it triggered right Action method (Capsule). The razor view page(.cshtml) where the above link is configured is not at the root. The action is invoked correctly because I have this configured in RouteConfig.Westfalen
@Kobi, you are right however in my case the content is in same server & hence above solution worked.Westfalen
Agree this is not the answer to the issue. welcome this downvote.Westfalen

© 2022 - 2024 — McMap. All rights reserved.