简体   繁体   中英

How to work conditional razor template c#

i was trying this code but getting error at run time. i want if IsUPS has true value then a new table row & table data will be added to table if IsUPS is false then table will have one table row and data? how to achieve this with razor template? please guide. thanks

    string template = "<table><tr><td>This is my sample template, 
    Hello @Model.Name!</td></tr> @if (@Model.IsUPS) {<tr><td> it is ups</td></tr> } 
    </table>";

    string result = Razor.Parse(template, new { Name = "World", IsUPS = true });

Assuming your "string result =" line works correctly;

There's quite a few things I would do differently here.

The error message (you should really have shared what the error is), related to your use of "@".

Try this:

@{
string template = @"<table><tr><td>This is my sample template, Hello" + this.Model.Name + @"!</td></tr>";

if (true)
{
    template += @"<tr><td> it is ups</td></tr>";
}

template += @"</table>";
}

The "@{ }" block encapsulates the html in a razor block so the use of @ for razor changes. Please note I have made the strings use @"" rather than "" so that if you want to split the html between lines you won't need to have string concatenation.

Firstly: I believe that an error produces a following statement:

@if (@Model.IsUPS) 

it should rather be:

@if (Model.IsUPS) 

after first @ you should put server-side code, so another @ is not neccessary when writing condition.

Secondly: Is the template pasted in one-line? If not, you need to use verbatim string:

string template = @"<table><tr><td>This is my sample template, 
                    Hello @Model.Name!</td></tr> @if (Model.IsUPS) {<tr><td> it is ups</td></tr> } 
                    </table>";

Thirdly: show us an error you get. Are you using RazorEngine library?

Fourth: after my fixes that code should work, checked myself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM