如何编写 razor 查询以并排显示两个字段



我正在使用foreach循环动态生成字段。我对渲染这些字段有几个条件。有一个条件是,如果为 true,则有两个字段应在同一行上并排呈现。我尝试了所有可能的方法,但它没有按照我想要的方式呈现。我不能使用 <div class="form-group">,因为它会在单独的行上显示字段。那么,我应该如何编写与引导程序代码相结合的 razor 查询,以便我有两个并排字段。这是我当前的代码:

@foreach (var d in data)
{
    if (Condition1)
    {
        <div class="form-group">
            <label class="col-sm-3 control-label">
                Text 1
            </label>
            <div class="col-sm-8">
                @Html.TextBox("Box1")
            </div>
        </div>
    }
    else if(Condition 2)
    {
        <div class="form-group">
            <label class="col-sm-3 control-label">
                Text 2
            </label>
            <div class="col-sm-8">
                @Html.TextBox("Box2")
            </div>
        </div>
    }
     else if(Condition3)
     {
        <form class="form-inline">
            <label class="required col-sm-3 control-label">
                @*Horsepower and RPM*@
            </label>
            <div class="col-sm-2">
                @{
                    @Html.TextBox("Box2")
                }
            </div>
        </form>       
     }
}

条件 3 是我想渲染这两个字段的位置这是我目前的状态:检查马力或 rpm

http://jsbin.com/nalexuredo/edit?html,output

您可以执行以下操作

  1. 使用index将您的foreach转换为for
  2. 检查index%2==0是否为真,这意味着您必须继续新行,但在这里您有两个选择

    • 开头的循环=> index is equal 0称之为A:你需要添加form-group
    • 不在开头的循环=> index >0称之为B:您需要关闭上一个div并添加新form-group

逻辑

 if(index%2 ==0)
    {
        if(index>0) // works with the case B
        {
            </div>
        }
        <div class="form-group">
    }
    ....
  1. 最后,一旦你离开for循环,你需要添加</div>

下面是一个代码示例:

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var list = new List<Data>()
            {
                new Data{Value="Val 1"},
                new Data{Value="Val 2"},
                new Data{Value="Val 3"},
                new Data{Value="Val 4"},
                new Data{Value="Val 5"},
                new Data{Value="Val 6"},
                new Data{Value="Val 7"}
            };
            return View(list);
        }

    }
    public class Data
    {
        public string Value { get; set; }
    }
}

视图 CSHTML

@model List<WebApplication1.Controllers.Data>
@{
    ViewBag.Title = "Home Page";
}

@for (var index = 0; index < Model.Count; index++)
{
    if (index % 2 == 0)
    {
        if (index > 0)
        {
            @:</div>
        }
        @:<div class="row">
    }
    <div class="col-md-6">
        @Model[index].Value @* here you can add whatever you want to represent your code*@
    </div>
}
@if (Model.Count > 0)
{
    @:</div>
}

备注:例如,如果要每行显示3列=>请使用index%3class="col-md-4"等等。

希望这对你有帮助

最新更新