MVC Razor for loop

后端 未结 6 1312
小鲜肉
小鲜肉 2021-02-13 10:16

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         


        
相关标签:
6条回答
  • 2021-02-13 10:57

    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"))) />
    } 
    
    0 讨论(0)
  • 2021-02-13 10:59

    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

    0 讨论(0)
  • 2021-02-13 11:02

    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.

    0 讨论(0)
  • 2021-02-13 11:10

    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"))) />
        }
     } 
    
    0 讨论(0)
  • 2021-02-13 11:18

    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"))           
        }
    
    0 讨论(0)
  • 2021-02-13 11:22

    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

    0 讨论(0)
提交回复
热议问题