繁体   English   中英

在ViewModel中使用@ Html.TextBoxFor

[英]Using @Html.TextBoxFor with ViewModel

一个简单的问题:

因此,我正在开发一个小型MVC / C#应用程序,并且正在使用ViewModel将数据传递到视图。 ViewModel实际上是3个模型的组合。

我的模特:

public class Sourcing_ProfileSourcingAreas
{
    public string Area { get; set; }

    public string Details { get; set; }
}


public class DefCountry
{
    public string CountryName { get; set; }

    public string CountryCode { get; set; }
}

我的ViewModel:

public class SourcingIndex
{
    public List<DefCountry> CountryLst { get; set; }

    public List<Sourcing_ProfileSourcingAreas> AreaLst { get; set; }
}

在我看来,我将此行放在@model SourcingIndex的顶部,以声明我将使用此ViewModel。

我还可以轻松地通过使用foreach循环来指定要显示的模型,例如:

@foreach (Sourcing_ProfileSourcingAreas area in Model.AreaLst)
    {
          <tr>
              <td>@area.Area</td>
              <td>@area.Details</td>                  
          </tr>           
    }

@foreach (DefCountry ctry in Model.CountryLst)
{
    <option>@ctry.CountryName</option>
}

但是,我无法创建@Html.TextBox并将其分配给模型中的特定属性!

如果可能的话,我希望它像这样: @Html.TextBoxFor(model => model.AreaLst.Area)

谢谢

关于Razor有点古怪。 如果尝试在foreach循环中访问对象,则很难确定模型在哪里。 您需要使用以下语法:

@for (int x = 0; x < Model.CountryLst.Count(); x++)
{
    @Html.TextBoxFor(t => t.CountryLst[x].CountryName)
}

这应该产生一个类似的输入

<input name="countryLst[1].CountryName"/>
@for(var i = 0; i < Model.CountryLst.Count(); i++)
{
    <text>@Html.TextBoxFor(p=>Model.CountryLst[i].CountryCode)</text>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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