1

I am working on project using asp.net mvc3 C# . I want to change some html element

attributes by c# like width , height etc. I have a simple (_Layout.cshtml) file

    <html> <head>
    <link href="@Url.Content("file.css")" rel="stylesheet" type="text/css" />
    <body>

     <a href="#" id="link1" title="@Function.ConfigElement("FacebookLink")" ></a>

     </body>
    </head> </html>

So i am using html agility pack to load and save this file

HtmlDocument doc= new HtmlDocument();

doc.load("_Layout.cshtml");

doc.GetElementbyId("link1").Attributes.Add("title", "@Function.ConfigElement("NewLink")");

doc.save("_Layout.cshtml");

After saving file output is like this

<html> <head>
        <link href="@Url.Content("file.css")"="" rel="stylesheet" type="text/css" />
        <body>

         <a href="#" id="link1" title="@Function.ConfigElement("NewLink")"="" ></a>

         </body>
        </head> </html>

in (link href) and (anchor title) saving some extra characters

How can i avoid this problem .. Is there any other solution for parse html in c# for asp.net mvc.

Actually I want to add some server side function in these html element attributes

Shoaib Ijaz
  • 5,347
  • 12
  • 56
  • 84
  • I suppose you could just do a `string.Replace("=\"\"", "");` to strip out the extra characters. That *is* a little weird, though. – Robert Harvey Dec 06 '12 at 19:16

2 Answers2

3

As StackOverflow's syntax highlight subtly hints, your HTML is extremely invalid.

href="@Url.Content("file.css")"

This is actually two attributes: href="@Url.Content(" and file.css")". (which has no value)

You can't use an HTML parser to parse Razor markup.
Instead, you should use the actual Razor parser.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

CSCHTML is not HTML. It is mix of CS, special scripts and optionally HTML - so HtmlAgilityPack is not a good tool to read/manipulate it.

Why it happens in particular:

<link href="@Url.Content("file.css")" 

Form HTML point of view there are 2 attributes and (href and file.css) plus strange ")" unexpected text. Somehow AgilityPack tries to make sense of it and outputs whatever you got.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 1
    Actually, the `")"` is part of the second attribute. (since there is no `=`) – SLaks Dec 06 '12 at 19:25
  • @SLaks, probably - have not read HTML spec that carefully to know if attribute name ends on "=" or anything that is not letters... In any case it just not reasonable HTML element. (you already gave correct answer :) ) – Alexei Levenkov Dec 06 '12 at 19:33