MVC Razor for loop

2019-04-05 05:32发布

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?

6条回答
疯言疯语
2楼-- · 2019-04-05 05:50

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.

查看更多
爷、活的狠高调
3楼-- · 2019-04-05 05:52

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

查看更多
Juvenile、少年°
4楼-- · 2019-04-05 05:55

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"))           
    }
查看更多
欢心
5楼-- · 2019-04-05 05:57

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"))) />
    }
 } 
查看更多
对你真心纯属浪费
6楼-- · 2019-04-05 06:00

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"))) />
} 
查看更多
登录 后发表回答