MVC Razor for loop

2019-04-05 05:31发布

问题:

I have this code (nested inside a form post) but am continually getting the error that it's missing the closing }

@for(int i=0;i< itemsCount; i++){
    <input type="hidden" @string.Format("name= item_name_{0} value= {1}",i,items[i].Description) >
    <input type="hidden" @string.Format("name= item_name_{0} value= {1}",i,items[i].UnitPrice.ToString("c"))>
} 

I've been staring at it long enough...can anyone help?

回答1:

Try put @: before your html code like this:

 @for(int i=0;i< itemsCount; i++)
 {
    @: html code here
 } 

Alternatives: 1. wrap your html code with <text></text> 2. use HtmlHelper to generate the html code



回答2:

you may note that for writing a code block you can write in two ways

  1. For Only a line of Block ,just like you have written in your code and this encloses just the line that contains the preceding @
  2. For Code Block using @{... } ,this gives you freedon to use Code without preceding @ except within HTML expressions .for any html/text you must precede it with @: you want to print as is,otherwise Razor will try to interpret it as code(Since @: defines content as literal for every code expression under @: you must use @ again for code)

In your case you can do as following

@{
    for(int i=0; i < itemsCount; i++)
    {
       @:<input type="hidden" @Html.Raw(string.Format("name= item_name_{0} value=  {1}",i,items[i].Description)) />
       @:<input type="hidden" @Html.Raw(@string.Format("name= item_name_{0} value= {1}",i,items[i].UnitPrice.ToString("c"))) />
    }
 } 


回答3:

Easiest way is to make use of HTML Helpers. Code will be clean as well (your name format for Description and UnitPrice seems to follow the same format; you may want to change it)

    @for (int i = 0; i < itemsCount; i++)
    {
        @Html.Hidden(string.Concat("ïtem_name_", i), items[i].Description)
        @Html.Hidden(string.Concat("ïtem_name_", i), items[i].UnitPrice.ToString("c"))           
    }


回答4:

Or you can use the Html.Raw helper

@for(int i=0; i < itemsCount; i++)
{
    <input type="hidden" @Html.Raw(string.Format("name= item_name_{0} value= {1}",i,items[i].Description)) />
    <input type="hidden" @Html.Raw(@string.Format("name= item_name_{0} value= {1}",i,items[i].UnitPrice.ToString("c"))) />
} 


回答5:

try:

@for (int i = 0; i < itemsCount; i++) {
    <input type="hidden" name="@("item_name_" + i)" value="@items[i].Description" />
    <input type="hidden" name="@("item_name_" + i)" value="@(items[i].UnitPrice.ToString("c"))" />
}

Note the changes / notes in prashanth's another as well.



回答6:

Try to enclose your for loop body between text tag.

http://weblogs.asp.net/scottgu/archive/2010/12/15/asp-net-mvc-3-razor-s-and-lt-text-gt-syntax.aspx