SCD SCD - 1 year ago 85
ASP.NET (C#) Question

IF condition with <div> in the view file of MVC

I am able to pass data to view file, but need to display them in different format with .
I try to use if statement to check the form name.
It returns error said "Operator '==' cannot be applied to operands of type 'System.Web.HtmlString' and 'string'".
Can I add blocks within IF condition? how to validate data within if condition in view file? Thank you! Here is the code:

@{ foreach (var form in @ViewBag.FormContent) {if (Html.Raw(form.Name) == "xyz") //pull up the title and text for the form {@Html.Raw(form.FormTitle)


} }

Answer Source

HTML.Raw returns an object that implements IHtmlString. It does not return a string. It doesn't even support ToString. Its only member is ToHtmlString(), which returns a string.

If you want to compare the output of Html.Raw with "xyz", you need to convert it to a string first. So instead of

if (Html.Raw(form.Name) == "xyz")

use something like

if (Html.Raw(form.Name).ToHtmlString() == "xyz")

Or... don't even bother with Html.Raw to begin with. Don't think you need it. Just write this:

if (form.Name == "xyz")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download